How to set onclick listener for a button in a fragment in android
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);
}
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
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.