Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set onClick listener for a Fragment?

I am working with Android Studio. I have a fragment on my Activty and I want to hide it when the user clicks on it.

For some reason I can´t just override a function for onclick like in the activties. And everytime I ask google all I can find are questions about how to Implement onclick listeners for buttons or other elements in a fragment but that is not what I want. I want the onclick listener for the fragment itself.

Can anyone please tell me how to do that!?

like image 729
joohaha Avatar asked Jan 06 '16 09:01

joohaha


People also ask

What is set onClick listener?

OnClickListener and wires the listener to the button using setOnClickListener(View. OnClickListener) . As a result, the system executes the code you write in onClick(View) after the user presses the button. The system executes the code in onClick on the main thread.

How do you make toast in a fragment?

This is how you can show an Android Toast message from a Fragment: Toast. makeText(getActivity(), "Click!", Toast.


2 Answers

You can do this by set ClickListener on the view inflating in a onCreateView of fragment like this :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
 View v=inflater.inflate(R.layout.layout_your, container, false);
    v.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //do your operation here
            // this will be called whenever user click anywhere in Fragment
        }
    });
 return v;
}
like image 99
Kapil Rajput Avatar answered Nov 15 '22 06:11

Kapil Rajput


It goes like below

public class fragmentOne extends Fragment implements OnClickListener {
    Button myButton;

    @Override
    public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState) {
        View myView = inflater.inflate(R.layout.fragment_1, container, false);
        myButton = (Button) myView.findViewById(R.id.myButton);
        myButton.setOnClickListener(this);
        return myView;
    }

    @Override
    public void onClick(View v) {
        // implements your things
    }
}
like image 23
johnrao07 Avatar answered Nov 15 '22 08:11

johnrao07