首页 > 解决方案 > 如何在android studio中从一个活动导航到另一个活动的片段?

问题描述

我收到一个错误

 public void on_Image_Button_9_Clicked(View view)
    {
        Intent click 5=new Intent(home.this,category 2.class);
        start Activity(click 5);
    }

// 类别 2 是片段

标签: android

解决方案


你的方法是错误的。要访问一个片段,您需要创建一个 FragmentTransaction。

我邀请您阅读本指南,了解 Fragment 如何防止使用它的任何不良习惯。

因此,要么调用包含所需片段的活动,要么将片段加载到当前容器中。

要将片段添加到活动中,您可以在活动的布局中声明它:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment"
        android:id="@+id/list"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />
<fragment android:name="com.example.news.ArticleReaderFragment"
        android:id="@+id/viewer"
        android:layout_weight="2"
        android:layout_width="0dp"
        android:layout_height="match_parent" />
</LinearLayout>

或者将容器添加到您的活动并使用 FragmentTransaction 在容器内显示您的片段:

myActivity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout android:id="@+id/myContainer"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

我的活动.java

 public class MyActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.myActivity_layout);
            setFragment()
        }


        public void setFragment() {
            // Create new fragment and transaction
            Fragment newFragment = new ExampleFragment();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

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

            // Commit the transaction
            transaction.commit();
        }
    }

推荐阅读