Fragement getArguments()返回null

时间:2016-10-16 21:00:50

标签: android android-fragments

我正在尝试将数据从我的活动传递到片段但是我在Bundle.getString()上得到一个空指针

我也注意到,即使没有片段交易代码

也会进入片段

片段:

public class MainFragment extends BrowseFragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = this.getArguments();
        String myValue = bundle.getString("message");
    }

活动

public class MainActivity extends FragmentActivity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Bundle bundle = new Bundle();
        String myMessage = "Stackoverflow is cool!";
        bundle.putString("message", myMessage );
        MainFragment fragInfo = new MainFragment();
        fragInfo.setArguments(bundle);
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.main_browse_fragment, fragInfo);
        transaction.commit();
    }

activity_main.xml中

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_browse_fragment"
    android:name="my.package.MainFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:deviceIds="tv"
    tools:ignore="MergeRootFrame" />

1 个答案:

答案 0 :(得分:2)

将xml布局中的片段更改为简单的FrameLayout。从xml创建片段会导致异常,因为它没有参数(它们是在您的Activity代码中手动添加的)