I have a problem with finding buttons. I have an AlertDialog
where I choose one of 5 options. When I choose an option I want change the color of the button I clicked. I declared buttons in xml file inside <RealativeLayout>
but when I'm trying to find my button by id (id's are like "id1","id2"...)using the findViewById
method, there is a mistake, which says that I can't use this method like I do:
AlertDialog.Builder builder = new AlertDialog.Builder(StartGameActivity.this);
builder.setTitle(R.string.pickColor);
builder.setItems(R.array.colorArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Button btn_tmp;
String theButtonId = "id";
theButtonId = theButtonId+(String.valueOf(which));
btn_tmp = (Button) findViewById(theButtonId);
}
});
How can I fix that or maybe I should use other method?
EDIT:
I think I solved my problem. I used one of Button's method: getId() like this:
final int id = clickedButton.getId();
final ImageButton btn_tmp;
btn_tmp = (ImageButton)findViewById(id);
Get the ID of clicked button using JavaScript. Example 1: This example sets a onClick event to each button, when button is clicked, the ID of the button is passed to the function then it prints the ID on the screen. <!DOCTYPE HTML>. <html>.
This is super useful, because it makes all of the code we wrote initially unnecessary. The way it works is basically it calls findViewById itself and it creates a cache of views it references any time you want to access that view again.
But In Kotlin, there is a new awesome way to use them without wasting time on writing findViewByIds. Add the ‘kotlin-android-extensions’ plugin to the top of the app level gradle file. But you don’t have to do it manually.
btn_tmp = (Button)findViewById(R.id.YourButtonId);
You are passing string instead of integer.
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