converting activity into fragment

后端 未结 4 824
一个人的身影
一个人的身影 2020-11-27 13:11

This is a simple code to play a sound on click off a button, this code was initially written in Activity but now i want to change it to Fragments.

erro

相关标签:
4条回答
  • 2020-11-27 13:55
    1. Fragment has a method called onCreateView(LayoutInflater, ViewGroup, Bundle). Override it, inflate using the layout and return the view.
    2. Since create method expects a Context, pass it using getActivity()
    3. findViewById(int) can be called as getView().findViewById(R.id.button3)

    Here is a sample code:

    public class Rajathmusic extends Fragment {
    
        private static final String TAG = "MyActivity";
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            return inflater.inflate(R.layout.activity_main, container, false);
        }
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            Log.v(TAG, "Initializing sounds...");
    
            final MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.rajath);
    
            View v = getView();
    
            Button play_button = (Button) v.findViewById(R.id.button3);
    
            play_button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Log.v(TAG, "Playing sound...");
                    mp.start();
                }
            });
            Log.v(TAG, "Sounds initialized.");
        }
    
    }
    

    Read more about Fragment lifecycle here to know why I've put the code in onActivityCreated and not onCreate

    0 讨论(0)
  • 2020-11-27 13:58

    Copy the code from the onCreate() method from the activity and paste it into the onCreateView() method of the fragment.

    To fix the errors, pass getActivity in place of this keyword and use getView().findViewById().

    0 讨论(0)
  • 2020-11-27 14:06

    In fragment onCreate method is usually written as-

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

    And Use-

    final MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.rajath);
    Button play_button = (Button) view.findViewById(R.id.button3);
    

    If you want to read more about fragments. Check this link.

    0 讨论(0)
  • 2020-11-27 14:12

    Use this code in overriden method OnActivityCreated(...) and instead of this use getActivity(), since new fragment is not activity any more.

    0 讨论(0)
提交回复
热议问题