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!?
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.
This is how you can show an Android Toast message from a Fragment: Toast. makeText(getActivity(), "Click!", Toast.
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;
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With