如何在Android Studio中从一个活动导航到另一个活动的片段?

时间:2019-03-29 14:58:32

标签: android

我遇到错误

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

// 2类是片段

1 个答案:

答案 0 :(得分:0)

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

我邀请您阅读how fragments work上的本指南,以防止使用它的任何不良习惯。

因此,您可以调用包含所需片段的活动,或者将片段加载到当前容器中。

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

<?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>

myActivity.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();
        }
    }