【发布时间】:2016-11-01 17:02:30
【问题描述】:
我在 Android Studio 2.2.2 中使用 Navigation Drawer Activity 模板创建了新项目。我决定使用 FrameLayout,所以当我点击导航菜单项时,会加载新的片段。
在我的 content_main.xml 我有这样的 FrameLayout 元素:
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
这是显示内容的框架。
然后我有布局 fragment_one.xml 及其类 FragmentOne,它们看起来像这样:
fragment_one.xml
<Button
android:text="Default Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/mybutton" />
FragmentOne 类
public class FragmentOne extends Fragment {
Button btn;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
btn = (Button) view.findViewById(R.id.mybutton);
return view;
}
public void changeBtnText(String txt)
{
btn.setText(txt);
}
}
在 MainActivity 的 onCreate() 方法中我有代码:
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new FragmentOne()).commit();
FragmentOne fragment_obj = (FragmentOne)getSupportFragmentManager().
findFragmentById(R.id.frOne);
fragment_obj.changeBtnText("Changed text");
这里我得到错误:
尝试在空对象引用上调用虚拟方法“void com.example.user.myapplication.FragmentOne.changeBtnText(java.lang.String)”
如何使用 changeBtnText(String txt) 方法从 Main Activity 更改片段的 按钮文本?
【问题讨论】:
标签: android android-fragments nullpointerexception android-button