How to set onclick listener for a button in a fragment in android

前端 未结 3 1044
星月不相逢
星月不相逢 2020-12-16 03:58

My app contains a form as shown in the following image:

\"register

When I click on menu o

相关标签:
3条回答
  • 2020-12-16 04:12

    First of all remember to implements the OnClickListener interface:

    public class YourClassName extends Fragment implements View.OnClickListener
    
    public Button button;
    

    Then, inside the method OnCreateView, inflate the button and set the listener to it, like this:

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
    
        button = (Button) inflater.inflate(R.layout.registerblood, container, false).findViewById(R.id.your_button_id);
        button.setOnClickListener(this);
    
    }
    

    Then @Override the function onClick and do whatever you gotta do:

    @Override
    public void onClick(View v) {
        //YOUR CODE HERE
    }
    

    EDIT If you're simply looking for a FocusListener (in that case your question needs an update) set the listener on your onCreateView method:

    your_edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
    
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            Toast.makeText(getApplicationContext(), "got the focus", Toast.LENGTH_LONG).show();
            // OPEN THE DRAWER HERE
        } else {
             Toast.makeText(getApplicationContext(), "lost the focus", Toast.LENGTH_LONG).show();
        }
    }
    

    or you can implement that listener to your class.

    0 讨论(0)
  • 2020-12-16 04:19

    Since the button is a part of the fragment's layout, set the listener there:

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
        View view = inflater.inflate(R.layout.registerblood, container, false);
        String menu = getArguments().getString("Menu");
        location = (Button) view.findViewById(R.id.etlocation);
        location.setText(menu);
        location.setOnClickListener(this);
    
        return view;
    }
    
    @Override
    public void onClick(View v) {
        RegisterBlood activity = (RegisterBlood) getActivity();
        // Now you can contact your activity through activity e.g.:
        activity.onKeyDown(KeyEvent.KEYCODE_MENU, null);
    }
    
    0 讨论(0)
  • 2020-12-16 04:27

    u need to inflate fragment like this for button click

      View view = inflater.inflate(R.layout.fragment_blank3,
                container, false);
       Button bt1=(Button)view.findViewbyId(R.id.buttton);
       bt1.setOnclick...
       //then return in on create view.
        return view;
    

    // this works good, thankyou

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