如何从活动中调用片段?

时间:2018-06-08 09:18:46

标签: android android-fragments android-activity android-gridview

在Activty中创建的Gridview。 Gridview Clickevent调用片段,但不调用Fragment。 Android Studio没有给出任何错误。

我创建了Home片段。

活动不是对Home Fragment的调用,也没有给出任何错误。

activity_main.xml中

<FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/frameLayout"/>

MainActivity.java

gridViewGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        switch (position){

            case 0 :

               Fragment fragment = new Home();
               FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
               transaction.replace(R.id.frameLayout, fragment); // fragment container id in first parameter is the  container(Main layout id) of Activity
               transaction.addToBackStack(null);  // this will manage backstack
               transaction.commit();

            break;
}}}

1 个答案:

答案 0 :(得分:0)

尝试使用FragmentManager:

Fragment fragment = null;
Class FragmentClass = Home.class;
try {
    fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
    e.printStackTrace();
}

FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
    .beginTransaction()
    .addToBackStack(null) // your manage backstack here
    .replace(R.id.frameLayout, fragment)
    .commit();

注意它是重要的:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;