Button Listener for button in fragment in android

后端 未结 9 2108
北恋
北恋 2020-12-02 11:04

I am new to Android and trying to learn on my own. But I am having a tough time with Fragments. I am creating a simple application to learn fragments. I think it may seem si

9条回答
  •  一向
    一向 (楼主)
    2020-12-02 11:21

    Simply pass view object into onButtonClicked function. getView() does not seem to work as expected inside fragment. Try this code for your FragmentOne fragment

    PS. you have redefined object view in your original FragmentOne code.

    package com.example.fragmenttutorial;
    
    import android.app.Fragment;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    public class FragmentOne extends Fragment{
    
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.fragment_one, container, false);
            onButtonClicked(view);
            return view;
        }
    
      protected void onButtonClicked(View view)
      {
          if(view.getId() == R.id.buttonSayHi){
              Fragment fragmentTwo = new FragmentTwo();
    
              fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
              fragmentTransaction.addToBackStack(null);
    
              fragmentTransaction.commit();   
    
         }
    

提交回复
热议问题