1

我正在尝试学习如何将片段用作 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();


}

代码编译并上传到平板电脑没有问题。我希望它会写出“我被压了!”的文字。按下按钮时到文本视图,但应用程序只是崩溃并显示标准“不幸的是应用程序已停止工作”。我还没有实现一个类来捕获这个未捕获的异常——我希望这可能是我遗漏或不理解的明显东西?

谢谢

4

1 回答 1

2

尽管这是一个老问题,但我想回答它,因为我很困惑为什么您的示例代码不起作用。

您获得 a 的原因NullPointerException是您实例化Fragment并立即调用需要将活动注入片段的方法。活动由FragmentManager/FragmentTransaction#commit方法注入,但此方法不会立即评估事务(来自 JavaDocs):

安排此事务的提交。提交不会立即发生;它将被安排在主线程上的工作,以便在该线程下一次准备好时完成。

意思是

getFragmentManager().beginTransaction().add(fragment, "updateText").commit();
fragment.startUpdateText();

将产生 NPE startUpdateText()(因为交易尚未执行!)。

通过在提交后立即添加方法调用getFragmentManager().executePendingTransactions();,事务将立即执行并将活动注入到片段中。getActivity()Fragment现在返回它附加到的 Activity 并且您的示例有效:)

从您的问题下面的评论来看:片段确实是托管在活动中的可重复使用的“用户界面元素”。@Stefan de Bruijn)而且[...]片段不需要成为活动布局的一部分;您也可以使用没有自己 UI 的片段作为活动的隐形工作者。(正如官方Android 文档所说)。

因此,片段不一定是 GUI 组件(即 MVC 中的视图),而是充当具有自己生命周期/生命周期的控制器。

于 2015-04-21T11:49:15.183 回答