我正在尝试学习如何将片段用作 android 活动的工作人员。我的主要活动有以下简单的 xml 布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press me" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
我使用以下类定义定义我的片段:
public class UpdateTextFragment extends Fragment {
public static UpdateTextFragment newInstance() {
return new UpdateTextFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void startUpdateText() {
TextView textView = ((TextView) getActivity().findViewById(R.id.text));
textView.setText("I've been pressed!");
}
}
然后从我的主要活动中,我只需添加片段并startUpdateText
使用按钮调用片段的方法onClickListener
,即
public void onClick(View arg0) {
UpdateTextFragment fragment = UpdateTextFragment.newInstance();
getFragmentManager().beginTransaction().add(fragment, "updateText").commit();
fragment.startUpdateText();
}
代码编译并上传到平板电脑没有问题。我希望它会写出“我被压了!”的文字。按下按钮时到文本视图,但应用程序只是崩溃并显示标准“不幸的是应用程序已停止工作”。我还没有实现一个类来捕获这个未捕获的异常——我希望这可能是我遗漏或不理解的明显东西?
谢谢