在Android中以编程方式设置片段ID与事务失败

时间:2015-10-14 11:03:13

标签: android android-fragments

我有3个碎片我添加到viewpageradapater,然后添加到我的MainActivity中的方法中的viewpager,在一段代码下面:

public class MainActivity extends AppCompatActivity implements FragmentCommunication {

...
       @Override
       protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            ...

            ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

            Resources res = getResources();

            adapter.addFragment(new FragmentOne(), res.getString(R.string.fragmentOneLabel));
            adapter.addFragment(new FragmentTwo(), res.getString(R.string.fragmentTwoLabel));
            adapter.addFragment(new FragmentThree(), res.getString(R.string.fragmentThreeLabel));
            viewPager.setAdapter(adapter);

            ...
        }

... 
...
    public void GetFragmentAndDoStuff(float[] values) {
        FragmentManager fm = getSupportFragmentManager();

        FragmentOne fragOne = (FragmentOne) fm.findFragmentByTag("my_fragmentone");
        // do stuff
    }
}

我将仅从现在开始关注FragmentOne作为示例。 我对FragmentOne的布局是一个相对布局,其中包含一些文本视图:

activity_fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="mypackage.Fragments.FragmentOne">

    <TextView .... />

</RelativeLayout>

和它关联的java类是(它的一部分):

public class FragmentOne extends Fragment {
  ...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.activity_fragment_one, container, false);

        view.setId(R.id.reservedFragmentOneID);

        FragmentManager fm = getActivity().getSupportFragmentManager();
        // Transaction start
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(view.getId(), this, "my_fragmentone");
        // Transaction commint
        ft.commit();

        return view;
    }
  ...
}

我的资源文件包含reservedFragmentOneID:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- List of reserved IDs -->
    <item name="reservedFragmentOneID" type="id"/>
</resources>

当我尝试在onCreateView中提交事务时,它会崩溃并停止工作。我也尝试使用container.setId(...)和container.getId()而不是使用视图,我得到了相同的行为。

那么,我做错了什么?

抛出异常:

Can't change tag of fragment FragmentOne{41f9e470 #1 id=0x7f0d0070 android:switcher:2131558512:0}: was android:switcher:2131558512:0 now my_fragmentone

最后,一旦我成功提交它,我想在我的MainActivity中通过其标签或ID获取FragmentOne,如下面的代码所示。我不确定我是否会使用上面的代码获得正确的片段(FragmentOne)或者使用null代替...,所以它是否正确?

1 个答案:

答案 0 :(得分:0)

可能RelativeLayout无效fragment

将activity_fragment_one.xml RelativeLayout的父级更改为FrameLayout