【问题标题】:How to update the content of a TextView in a fragment in navagation drawer in Android如何在Android导航抽屉的片段中更新TextView的内容
【发布时间】:2015-06-30 12:36:48
【问题描述】:

我是 Android 应用程序开发的新手。我正在尝试使用导航抽屉创建应用程序。我使用 android studio 使用导航抽屉模板创建了一个应用程序。然后我将其更改为每次用户在导航菜单中选择一个新项目时将其重定向到一个新的 fragment_layout。现在,我的第一个片段包含一个列表视图,单击列表中的一个项目我被重定向到一个包含 TextView 的详细片段。 当我尝试使用所选项目的详细信息填充此 TextView 时,我遇到了一个空指针异常。经过两天的研究并试图找出问题所在,我发现当我调用 fragment.isInLayout() 时,我的可见片段返回 false . 谢谢你的帮助。 我的代码: 创建一个新片段:

VideoDetailFragment fragment = new VideoDetailFragment(); 
Bundle bundle = new Bundle();
bundle.putString("title", title)
    fragment.setArguments(bundle); 
 FragmentTransaction transaction = getFragmentManager().beginTransaction();   
 transaction.replace(R.id.container, fragment);
       transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();

        getFragmentManager().executePendingTransactions();
        if (fragment.isInLayout()) {
            fragment.replaceText("Lalala");}  

而replaceText方法的代码是:

 public  void replaceText(String text){


textView.setText(text);
 }

问题是没有达到方法 replaceText 当我删除 if 语句时,会引发空指针异常,说我无法在 textView 中写入

编辑:我认为问题出在transaction.replace(R.id.container,fragment);,也许还有另一种替代片段布局内容的方法。因为,我在模拟器中显示了VideoDetailFragment,我无法更改它的内容,而且当我厌倦了VideoDetailFragment fragment1 = (VideoDetailFragment)getFragmentManager().findFragmentById(R.id.container); 时,它给了我一个演员表异常。 非常感谢您的帮助,非常需要它:)

【问题讨论】:

  • 您能发布不起作用的代码吗?否则很难弄清楚出了什么问题……
  • 尝试将getFragmentManager().executePendingTransactions(); if (fragment.isInLayout()) { fragment.replaceText("Lalala");} 放在transaction.commit(); 语句之前
  • 我也有同样的结果,无法到达fragment.replaceText("Lalala");

标签: android navigation-drawer


【解决方案1】:

尝试做这样的事情:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(key, value);
fragment.setArguments(bundle);

然后在您的第二个片段中,检索数据(例如,您可以在 onCreate() 中执行此操作):

Bundle bundle = this.getArguments();
int myString = bundle.getString(key, ""); //the second parameter is a default value

或者显示你的代码,看看你从哪里得到 NullPointerException

【讨论】:

    【解决方案2】:
    YourFragment fragment = getSupportFragmentManager().findFragmentById(R.id.your_fragment);
    
    if (fragment != null) {
       fragment.yourUpdateDataMethod(youData);
    }
    

    【讨论】:

    • 我认为我不能使用 findFragmentById,因为在我的主要活动中,我有两个片段,一个用于菜单,另一个称为“容器”用于页面内容。容器片段填充了 HomeFragment,我想用 VideoDetailFragment 替换它。
    • 我试过你的代码,不幸的是它引发了一个异常:HomeFragment cannot be cast to VideoDetailFragment。我认为问题是transaction.replace(R.id.container, fragment); 方法确实替换了模拟器中的布局,但它仍然像没有被替换一样工作,你知道为什么吗?谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 2014-07-23
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多