Search code examples
javaandroidstringimagebuttonfindviewbyid

android - findViewById using a String


I have many many ImageButtons,

and i want to use something to shortcut the code.

Like use findViewById method with a String value same findViewById("R.id.btn_name"),

or get button by tag,

or something like this.

Thanks in Advance.


Solution

  • You could do something like:

    int resourceId = this.getResources().getIdentifier("btn_name", "id", this.getPackageName());
    

    where this refers to the context/activity. Then use it as follows:

    ImageButton imageButton = (ImageButton) findViewById(resourceId);