Search code examples
androidandroid-fragmentsonclicklistenerbuttonclick

Open an activity from a Fragment in Android


Whenever I use or implement onClickListner in Fragment, the application crashes. I have tried all the methods like implementing the fragment class using on click in XML but the application crashes all the time. Please help me with this. I don’t even write anything in the onClick override method and still, the application crashes.

Button btn_edit;

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

     View rootView=inflater.inflate(R.layout.multi_frag,container,false);
     btn_edit=(Button)rootView.findViewById(R.id.edit);
     btn_edit.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {

         }
     });
     return inflater.inflate(R.layout.activity_account,container,false);
 }

Solution

  • The application is crashing because you are returning a different view and finding the button in a different view.

    // In below line you are using R.layout.multi_frag 
    
    View rootView=inflater.inflate(R.layout.multi_frag,container,false);
    btn_edit=(Button)rootView.findViewById(R.id.edit);
    btn_edit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
    
        }
    });
    // And here, you are returning R.layout.activity_account.
    
    return inflater.inflate(R.layout.activity_account,container,false);
    

    You cannot use two layouts within one fragment. Check the right layout which contains the button and use that layout in both of the places.