Ad
Android : Same OnClickListener On Many Buttons
I'm trying to set same OnClickListener on many buttons on one fragment.
So I tried to make the listener on top of the class such as
public class SigninUserInsurance extends Fragment {
Button.OnClickListener thisListener = new Button.OnClickListener(){
@Override
public void onClick(View v){
.....
}
}
However, I want to save what the button's text is. (button.getText()).
But in the ... section,
since the thisListener does not have witch button it is, and it only gets the view,
I can't call the getText(). v.getText() doesn't exists.
For example, I tried my code in ... section as following,
preferenceEditor.putString("User Insurance", Button.getText());
preferenceEditor.commit();
activity.fragChanger(4);
On the first line, Button.getText() can't be called because the thisListener does
not have the button information.
Is there any way without implementing every 10~ 20 button each own's listener??
Ad
Answer
You can define a listener object like this:
View.OnClickListener thisListener = new View.OnClickListener() {
public void onClick(View v) {
Button button = (Button) v;
switch (v.getId()) {
case R.id.button1:
preferenceEditor.putString("User Insurance", button.getText());
preferenceEditor.commit();
activity.fragChanger(4);
break;
case R.id.button2:
//
break;
//...............
}
}
}
and set this listener to all of your buttons:
button1.setOnClickListener(thisListener);
button2.setOnClickListener(thisListener);
..........................................
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad