在按钮单击时从另一个片段调用片段

时间:2016-02-11 19:49:37

标签: android-fragments

public class MasterDetailFragment extends Fragment {
    public interface onButtonItemSelected {
        public void onButtonItemSelected(int id);
    }
    onButtonItemSelected mListner;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Defines the xml file for the fragment
        View view = inflater.inflate(R.layout.masterdetail_fragment, container, false);
        // Setup handles to view objects here
        // etFoo = (EditText) view.findViewById(R.id.etFoo);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button _fragment0=(Button) getActivity().findViewById(R.id.button1);
        Button  _fragment1=(Button) getActivity().findViewById(R.id.button2);
        Button  _fragment2=(Button) getActivity().findViewById(R.id.button3);


        mListner=(onButtonItemSelected) getContext();
        _fragment1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int id = v.getId();
                System.out.println(" ************ GENERATED ID IS : " + id);

                if( id==R.id.fragment1) {
                    FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
                    fragTransaction.replace(R.id.masterdetail_fragment,new MovieDetailFragment() );
                    fragTransaction.addToBackStack(null);
                    fragTransaction.commit();
                    System.out.println(" ************ button1 " + id);
                }

            }
        });
        _fragment0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int id = v.getId();
                System.out.println(" ************ GENERATED ID IS : " + id);

                if( id==R.id.fragment0) {
                    mListner.onButtonItemSelected(R.id.myname);
                    System.out.println(" ************ button2 : " + id);
                }

            }
        });



    }
}

我正在尝试从按钮单击事件中的masterDetail片段加载movieDetail片段。 我无法添加movieDetail片段的新实例,因为它会抛出以下编译时错误。我该怎么做才能添加电影细节片段的新实例。

enter image description here

1 个答案:

答案 0 :(得分:0)

如果您想从当前片段类转到另一个片段,您应该使用

getChildFragmentManager()

而不是

getFragmentManager()

这解决了你的问题。