implementing OnClickListener for a fragment on android

前端 未结 4 1035
忘了有多久
忘了有多久 2021-01-05 10:18

I have a sliding menu project and inside home layout another layout is called as a fragment :

this is the HomeFragment.java :

package info.androidhiv         


        
4条回答
  •  抹茶落季
    2021-01-05 11:08

    While working with Fragment, you have to inflate view.

    So when you want to use any widget you have to use view object with findViewById().

    Simply Do like this...

    public class HomeFragment extends Fragment {
    
        public HomeFragment(){}
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    
            View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    
                btnCheckFalAction = (Button) rootView.findViewById(R.id.btnCheckFal); // you have to use rootview object..
                btnCheckFalAction.setOnClickListener(new OnClickListener() {           
    
                      @Override
                      public void onClick(View v) 
                      {
                          Toast.makeText(getActivity(), "Hello World", Toast.LENGTH_LONG).show();
                      }    
                    });
    
            return rootView;
        }
    }
    

    OR try other way..

    public class HomeFragment extends Fragment implements OnClickListener{
    
        public HomeFragment(){}
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    
            View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    
                btnCheckFalAction = (Button) rootView.findViewById(R.id.btnCheckFal); // you have to use rootview object..
                btnCheckFalAction.setOnClickListener(this);
    
            return rootView;
        }
        @Override
        public void onClick(View v) {
         // TODO Auto-generated method stub
         switch(v.getId()){
    
         case R.id.btnCheckFal :
             //your code...
         break;
    
        default:
            break;
    
         }
    
        }
    }
    

提交回复
热议问题