I have a lot of Buttons that I've created programatically, each button corresponds to a certain action, and I need to be able to identify and retrieve the user input based on which button was clicked. The UI is as follow:
I have like 70 items like those ones.
I've read
Dynamically creating Buttons and setting onClickListener
and
Implementing OnClickListener for dynamically created buttons in Android
But I do not know what is the correct approach. For example, if the user clicks in the Button
Text is now set... , I have to be able to retrieve the value of the EditText
, and know that this amount of minutes corresponds with Andar carrito compra .
Would be correct to assign a tag
to the Button
, in order to identify the index on the screen, and then go up in the View hierarchy and retrieve the EditText
Value?
This is my code so far:
for (int i = 1; i < types.length; i++) {
// ... more views created
// ......
Button enterBt2 = new Button(this);
// Set layout params and stuff for the button
enterBt2.setTag(i);
enterBt2.setOnClickListener(getOnClickDoSomething(enterBt2));
// ....
}
And the OnClickListener
:
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
Log.e(TAG, "O " + ExerciseRecord.TYPE.values()[((int) button.getTag())]);
// Obtain the value of the EditText with
LinearLayout ll = (LinearLayout) button.getParent();
ll.getChildAt(0); //The EditText
}
};
}
Would this be the best way to it?
Would be correct to assign a tag to the Button, in order to identify the index on the screen, and then go up in the View hierarchy and retrieve the EditText Value?
It is an option. Or you could have a class that implements the interface, adding a constructor with takes a String as parameter. Eg.
public class MyOnClickListener implements View.OnClickListener {
final String mValue;
public MyOnClickListener(String value) {
mValue = value;
}
public void onClick(View v) {
Log.e(TAG, "O " + mValue);
// Obtain the value of the EditText with button.getParent()....
}
}
That's one possible approach. The tag on a view is itself an object so, theoretically, you could put the edit text as the tag so it's easier for you to retrieve it, but you may have some memory leaks problems - I did this myself.
Another way, which I think it's an overkill, is to create a subclass of Button and add any information you require.
You should create a component managing the behaviour of title, edittext and button.
Hope this link helps: http://mobile.cs.fsu.edu/creating-a-simple-compound-component-in-android/
Regards
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.