【发布时间】: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");