How to handle button clicks using the XML onClick within Fragments

How to handle button clicks using the XML onClick within Fragments

Asked on December 16, 2018 in XML.
Add Comment


  • 3 Answer(s)

    Activity:

    Fragment someFragment;
     
    //...onCreate etc instantiating your fragments
     
    public void myClickMethod(View v) {
      someFragment.myClickMethod(v);
    }
    

    Fragment:

    public void myClickMethod(View v) {
      switch(v.getId()) {
        // Just like you were doing
    }
    }
    

    Also we can use,

    Interface:

    public interface XmlClickable {
      void myClickMethod(View v);
    }
    

    Activity:

    XmlClickable someFragment;
     
    //...onCreate, etc. instantiating your fragments casting to your interface.
    
    public void myClickMethod(View v) {
      someFragment.myClickMethod(v);
    }
    

    Fragment:

    public class SomeFragment implements XmlClickable {
     
    //...onCreateView, etc.
     
    @Override
    public void myClickMethod(View v) {
      switch(v.getId()){
      // Just like you were doing
    }
    }
    
    Answered on December 16, 2018.
    Add Comment

    Try this:

        For handling onClick events, Activity and Fragments works by below codes.

    public class StartFragment extends Fragment implements OnClickListener{
     
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
     
        View v = inflater.inflate(R.layout.fragment_start, container, false);
     
        Button b = (Button) v.findViewById(R.id.StartButton);
        b.setOnClickListener(this);
        return v;
      }
     
      @Override
      public void onClick(View v) {
        switch (v.getId()) {
        case R.id.StartButton:
     
          ...
     
          break;
        }
      }
    }
    
    Answered on December 16, 2018.
    Add Comment

    Simple solution:

         The view is still the activity but not the fragment. By its own the fragments does not have any absolute view by attached to the parent activities view. So the event get over the Activity, not the fragment. Adding a click listener that calls the old event handler during conversions may solve this.

    Example:

    final Button loginButton = (Button) view.findViewById(R.id.loginButton);
    loginButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(final View v) {
        onLoginClicked(v);
      }
    });
    
    Answered on December 16, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.