Android: Difficulty starting a fragment inside of a fragment

前端 未结 1 2029
面向向阳花
面向向阳花 2020-12-22 04:33

So, I previously asked a question, and got a bit of help, but ultimately, I decided that I needed to be more clear.

Basically, I have an app. The Main activity is a

相关标签:
1条回答
  • 2020-12-22 05:05

    I think the best way to implement this type of functionality is to use an interface callback from the Fragment to the Activity.

    Android Studio 1.2.2 will even automatically create interface callback code if you check the "Include interface callbacks?" checkbox when creating a new Fragment.

    Here is the general code structure for the Fragment:

    public class MainActivityFragment extends Fragment {
    
        private OnMainFragmentInteractionListener mListener;
        private Button exampleButton;
    
        public MainActivityFragment() {
        }
    
        public static MainActivityFragment newInstance() {
            MainActivityFragment fragment = new MainActivityFragment();
            return fragment;
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    
            exampleButton = (Button) rootView.findViewById(R.id.button);
    
            exampleButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.buttonClicked("test value");
                }
            });
    
            return rootView;
        }
    
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            try {
                mListener = (OnMainFragmentInteractionListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString()
                        + " must implement OnMainFragmentInteractionListener");
            }
        }
    
        public interface OnMainFragmentInteractionListener {
            void buttonClicked(String val);
        }
    }
    

    Then the Activity will implement the interface:

    public class MainActivity extends FragmentActivity
            implements MainActivityFragment.OnMainFragmentInteractionListener {
    

    And implement the interface method:

    @Override
    public void buttonClicked(String val) {
    
        FragmentManager fm = getFragmentManager();
        fragment = new DayViewFragment();
    
        FragmentTransaction ft = fm.beginTransaction();
        ft.addToBackStack(null);
        ft.add(android.R.id.content, fragment);
        ft.commit();
    
    }
    
    0 讨论(0)
提交回复
热议问题