Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: finding button by id

Tags:

java

android

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);
like image 695
Ziva Avatar asked Jan 11 '13 21:01

Ziva


People also ask

How to get the ID of clicked button in JavaScript?

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>.

What is the use of findviewbyid ()?

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.

How to use findviewbyids in Kotlin?

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.


1 Answers

btn_tmp = (Button)findViewById(R.id.YourButtonId);

You are passing string instead of integer.

like image 133
Ramesh Sangili Avatar answered Sep 21 '22 18:09

Ramesh Sangili