3

所以我有两个MAIN ACTIVITY(M)FRAGMENTS(F1, F2)一个BUTTON(B)F1

现在,当主要活动启动时F1会自动加载这很好,我想做的是F2在单击Bwhich is on时启动F1

以下是我的 Fragment1 代码,即 HomeFragment:

package info.androidhive.slidingmenu;

import java.lang.reflect.Field;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;

public class HomeFragment extends Fragment {

 public static HomeFragment newInstance() 
 {
        return new HomeFragment();
    }

public HomeFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState){


    View rootView = inflater.inflate(R.layout.fragment_home, container, false);

    ImageButton ib = (ImageButton) rootView.findViewById(R.id.buttonEnq);
    ib.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            InfoFragment infoFragment = new InfoFragment();
            /*FragmentManager fm = getFragmentManager();
            fm.beginTransaction().replace(R.id.frame_container, infoFragment).commit();
            */

            FragmentTransaction ft = getChildFragmentManager().beginTransaction();
            ft.setCustomAnimations(R.anim.abc_slide_out_bottom, 0);
            ft.replace(R.id.frame_container,infoFragment);
            ft.commit();
        }
    });

    ViewPager viewPager = (ViewPager)rootView.findViewById(R.id.myfivepanelpager);
    ImageAdapter adapter1 = new ImageAdapter(this.getActivity());
    viewPager.setAdapter(adapter1);

    return rootView;

    }

@Override
public void onDetach(){
    super.onDetach();

    try{

        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this,null);

    }catch(NoSuchFieldException e){
        throw new RuntimeException(e);
    }catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
  } 
}

frame_container是 中容器的名称main_activity.xml。我试过以下帖子:

你能告诉我我做错了什么吗?

4

1 回答 1

5

问题是您试图将 in 添加为Fragment B子片段,我怀疑这不是片段 A 布局(R.layout.fragment_home)中的视图。Fragment AR.id.frame_containerframe_container

您始终可以使用 getChildFragmentManager() 添加子片段,但它需要一个容器来保存片段。

在您的情况下,我认为不需要将 Fragment B 添加为 Fragment A 的子项。

您需要使用 Activity Fragment Manager 将 Activity 中附加的 Fragment A 替换为 Fragment B

更改ButtononClick()中的行

FragmentTransaction ft = getChildFragmentManager().beginTransaction();

作为

FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
于 2014-04-18T03:39:15.040 回答