Android 在片段抛出活动中更改类

Android 在片段抛出活动中更改类,android,android-fragments,Android,Android Fragments,我有三个片段和一个活动。 我已经将这两个片段并排放在活动中,我希望在单击第一个片段时,将其更改为第三个片段 活动: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_

我有三个片段和一个活动。 我已经将这两个片段并排放在活动中,我希望在单击第一个片段时,将其更改为第三个片段

活动:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:baselineAligned="false"
    android:orientation="horizontal" 
    android:id="@+id/parent">

    <fragment
        android:id="@+id/mainPage"
        android:layout_width="0dp"
        android:layout_weight="0.7"
        android:layout_height="wrap_content"
        class="com.example.user1.lotus.MainMenu" >
    </fragment>
    <fragment
        android:id="@+id/side_bar"
        android:layout_width="0dp"
        android:layout_weight="0.3"
        android:layout_height="wrap_content"
        class="com.example.user1.lotus.SideBar" >
    </fragment>

</LinearLayout>
在片段中

 btnMainDish.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            mListener.onFragmentInteraction("mainDish");
        }
    });

只需在按钮的onClick listener方法中执行此操作,您的片段将被第三个片段替换:

ThirdFragment newFragment = new ThirdFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.layout_replace, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

希望这有帮助。

如果单击第一个片段,应该会得到第三个片段,是吗?那肯定是可能的。是的,确实如此。我在第一个按钮上有一个按钮,点击它,它就会被第三个按钮所取代…谢谢你的投票。如果这对您有帮助,那么请接受它作为回答。java.lang.ClassCastException:com.example.user1.lotus.first\u fragm不能转换为com.example.user1.lotus.third\u fragm它给了我这些错误我已经在上面添加了抱歉,我忘记添加这一行,因为我正在试图同时查找错误`main menu fragment=(MainMenu)getFragmentManager().findFragmentById(R.id.mainPage);如果(fragment!=null&&fragment.isInLayout()){`在开关之前添加了…错误在此行中,当我擦除它时,不会发生任何事情..没有错误,但也不会替换。请在答案中检查我的编辑,抱歉,它的第三个片段newFragment=new ThirdFragment(),更改此项后,请让我知道它是否正常工作?
ThirdFragment newFragment = new ThirdFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.layout_replace, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();