Android: Using findViewById() with a string / in a loop
I'm making an android application, where there is a view composed of hundreds of buttons, each with a specific callback. Now, I'd like to set these callbacks using a loop, instead of having to write hundreds of lines of code (for each one of the buttons).
My question is: How can I use findViewById without statically having to type in each button id?
Here is what I would like to do:
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
buttons[i][j] = ((Button) findViewById(R.id.buttonID));
buttons[i][j].setOnClickListener(this);
}
}
Thanks in advance!

add a comment |
I'm making an android application, where there is a view composed of hundreds of buttons, each with a specific callback. Now, I'd like to set these callbacks using a loop, instead of having to write hundreds of lines of code (for each one of the buttons).
My question is: How can I use findViewById without statically having to type in each button id?
Here is what I would like to do:
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
buttons[i][j] = ((Button) findViewById(R.id.buttonID));
buttons[i][j].setOnClickListener(this);
}
}
Thanks in advance!

add a comment |
I'm making an android application, where there is a view composed of hundreds of buttons, each with a specific callback. Now, I'd like to set these callbacks using a loop, instead of having to write hundreds of lines of code (for each one of the buttons).
My question is: How can I use findViewById without statically having to type in each button id?
Here is what I would like to do:
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
buttons[i][j] = ((Button) findViewById(R.id.buttonID));
buttons[i][j].setOnClickListener(this);
}
}
Thanks in advance!

I'm making an android application, where there is a view composed of hundreds of buttons, each with a specific callback. Now, I'd like to set these callbacks using a loop, instead of having to write hundreds of lines of code (for each one of the buttons).
My question is: How can I use findViewById without statically having to type in each button id?
Here is what I would like to do:
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
buttons[i][j] = ((Button) findViewById(R.id.buttonID));
buttons[i][j].setOnClickListener(this);
}
}
Thanks in advance!


edited Feb 1 '11 at 16:56
Heiko Rupp
22.3k1170113
22.3k1170113
asked Feb 1 '11 at 16:35
user573536user573536
9553108
9553108
add a comment |
add a comment |
7 Answers
7
active
oldest
votes
You should using getIdentifier()
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = ((Button) findViewById(resID));
buttons[i][j].setOnClickListener(this);
}
}
Thanks, that was what I was looking for.
– user573536
Feb 1 '11 at 17:20
22
"com.sample.project" can be replaced by getPackageName().
– jenzz
Nov 17 '12 at 17:41
I'd seen other answers very similar to this, but the second arg being "id" was the last thing I needed for it to work.
– Dave C
Mar 28 '16 at 3:39
2
Note that in my experience doing this gives you very poor performance.
– ThomasW
Jun 28 '16 at 3:56
add a comment |
You can try making an int that holds all of your button IDs, and then iterate over that:
int buttonIDs = new int {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }
for(int i=0; i<buttonIDs.length; i++) {
Button b = (Button) findViewById(buttonIDs[i]);
b.setOnClickListener(this);
}
add a comment |
Take a look at these answers:
- Android and getting a view with id cast as a string
- Array of ImageButtons, assign R.view.id from a variable
1
@user573536 be aware that usinggetResources().getIdentifier()
in a loop can cause performance to degrade when you have a large number of lookups.
– dave.c
Feb 1 '11 at 16:47
You are right. I recommend that approach only when there's a sequence or order for the resources AND there are a lot of them (creating an array of 50 resources smells).
– Cristian
Feb 1 '11 at 17:03
add a comment |
you can Use tag if you want to access.
in onClick
int i=Integer.parseInt(v.getTag);
But you cant access that button like this.
simply create button programatically
by Button b=new Button(this);
add a comment |
create Custom Button in java code rather in Xml as i shown below
Button bs_text= new Button[some_value];
for(int z=0;z<some_value;z++)
{
try
{
bs_text[z] = (Button) new Button(this);
}
catch(ArrayIndexOutOfBoundsException e)
{
Log.d("ArrayIndexOutOfBoundsException",e.toString());
}
}
add a comment |
If your top level view only has those button views as children, you could do
for (int i = 0 ; i < yourView.getChildCount(); i++) {
Button b = (Button) yourView.getChildAt(i);
b.setOnClickListener(xxxx);
}
If there are more views present you'd need to check if the selected one is one of your buttons.
do you know how the performance compares with the other suggested methods? I'd assume that it was slightly slower than an array of ID's, but I'd be interested to know how it compares withgetResources().getIdentifier()
.
– dave.c
Feb 1 '11 at 16:58
No sorry no idea. A view knows his children, so I don't think it is too bad.
– Heiko Rupp
Feb 1 '11 at 21:26
add a comment |
If for some reason you can't use the getIdentifier()
function and/or you know the possible id's beforehand, you could use a switch.
int id = 0;
switch(name) {
case "x":
id = R.id.x;
break;
etc.etc.
}
String value = findViewById(id);
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4865244%2fandroid-using-findviewbyid-with-a-string-in-a-loop%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
You should using getIdentifier()
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = ((Button) findViewById(resID));
buttons[i][j].setOnClickListener(this);
}
}
Thanks, that was what I was looking for.
– user573536
Feb 1 '11 at 17:20
22
"com.sample.project" can be replaced by getPackageName().
– jenzz
Nov 17 '12 at 17:41
I'd seen other answers very similar to this, but the second arg being "id" was the last thing I needed for it to work.
– Dave C
Mar 28 '16 at 3:39
2
Note that in my experience doing this gives you very poor performance.
– ThomasW
Jun 28 '16 at 3:56
add a comment |
You should using getIdentifier()
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = ((Button) findViewById(resID));
buttons[i][j].setOnClickListener(this);
}
}
Thanks, that was what I was looking for.
– user573536
Feb 1 '11 at 17:20
22
"com.sample.project" can be replaced by getPackageName().
– jenzz
Nov 17 '12 at 17:41
I'd seen other answers very similar to this, but the second arg being "id" was the last thing I needed for it to work.
– Dave C
Mar 28 '16 at 3:39
2
Note that in my experience doing this gives you very poor performance.
– ThomasW
Jun 28 '16 at 3:56
add a comment |
You should using getIdentifier()
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = ((Button) findViewById(resID));
buttons[i][j].setOnClickListener(this);
}
}
You should using getIdentifier()
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = ((Button) findViewById(resID));
buttons[i][j].setOnClickListener(this);
}
}
edited Sep 15 '16 at 7:10
answered Feb 1 '11 at 16:44
WarrenFaithWarrenFaith
50k21124137
50k21124137
Thanks, that was what I was looking for.
– user573536
Feb 1 '11 at 17:20
22
"com.sample.project" can be replaced by getPackageName().
– jenzz
Nov 17 '12 at 17:41
I'd seen other answers very similar to this, but the second arg being "id" was the last thing I needed for it to work.
– Dave C
Mar 28 '16 at 3:39
2
Note that in my experience doing this gives you very poor performance.
– ThomasW
Jun 28 '16 at 3:56
add a comment |
Thanks, that was what I was looking for.
– user573536
Feb 1 '11 at 17:20
22
"com.sample.project" can be replaced by getPackageName().
– jenzz
Nov 17 '12 at 17:41
I'd seen other answers very similar to this, but the second arg being "id" was the last thing I needed for it to work.
– Dave C
Mar 28 '16 at 3:39
2
Note that in my experience doing this gives you very poor performance.
– ThomasW
Jun 28 '16 at 3:56
Thanks, that was what I was looking for.
– user573536
Feb 1 '11 at 17:20
Thanks, that was what I was looking for.
– user573536
Feb 1 '11 at 17:20
22
22
"com.sample.project" can be replaced by getPackageName().
– jenzz
Nov 17 '12 at 17:41
"com.sample.project" can be replaced by getPackageName().
– jenzz
Nov 17 '12 at 17:41
I'd seen other answers very similar to this, but the second arg being "id" was the last thing I needed for it to work.
– Dave C
Mar 28 '16 at 3:39
I'd seen other answers very similar to this, but the second arg being "id" was the last thing I needed for it to work.
– Dave C
Mar 28 '16 at 3:39
2
2
Note that in my experience doing this gives you very poor performance.
– ThomasW
Jun 28 '16 at 3:56
Note that in my experience doing this gives you very poor performance.
– ThomasW
Jun 28 '16 at 3:56
add a comment |
You can try making an int that holds all of your button IDs, and then iterate over that:
int buttonIDs = new int {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }
for(int i=0; i<buttonIDs.length; i++) {
Button b = (Button) findViewById(buttonIDs[i]);
b.setOnClickListener(this);
}
add a comment |
You can try making an int that holds all of your button IDs, and then iterate over that:
int buttonIDs = new int {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }
for(int i=0; i<buttonIDs.length; i++) {
Button b = (Button) findViewById(buttonIDs[i]);
b.setOnClickListener(this);
}
add a comment |
You can try making an int that holds all of your button IDs, and then iterate over that:
int buttonIDs = new int {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }
for(int i=0; i<buttonIDs.length; i++) {
Button b = (Button) findViewById(buttonIDs[i]);
b.setOnClickListener(this);
}
You can try making an int that holds all of your button IDs, and then iterate over that:
int buttonIDs = new int {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }
for(int i=0; i<buttonIDs.length; i++) {
Button b = (Button) findViewById(buttonIDs[i]);
b.setOnClickListener(this);
}
answered Feb 1 '11 at 16:39
Rick BarkhouseRick Barkhouse
6771512
6771512
add a comment |
add a comment |
Take a look at these answers:
- Android and getting a view with id cast as a string
- Array of ImageButtons, assign R.view.id from a variable
1
@user573536 be aware that usinggetResources().getIdentifier()
in a loop can cause performance to degrade when you have a large number of lookups.
– dave.c
Feb 1 '11 at 16:47
You are right. I recommend that approach only when there's a sequence or order for the resources AND there are a lot of them (creating an array of 50 resources smells).
– Cristian
Feb 1 '11 at 17:03
add a comment |
Take a look at these answers:
- Android and getting a view with id cast as a string
- Array of ImageButtons, assign R.view.id from a variable
1
@user573536 be aware that usinggetResources().getIdentifier()
in a loop can cause performance to degrade when you have a large number of lookups.
– dave.c
Feb 1 '11 at 16:47
You are right. I recommend that approach only when there's a sequence or order for the resources AND there are a lot of them (creating an array of 50 resources smells).
– Cristian
Feb 1 '11 at 17:03
add a comment |
Take a look at these answers:
- Android and getting a view with id cast as a string
- Array of ImageButtons, assign R.view.id from a variable
Take a look at these answers:
- Android and getting a view with id cast as a string
- Array of ImageButtons, assign R.view.id from a variable
edited May 23 '17 at 11:55
Community♦
11
11
answered Feb 1 '11 at 16:40
CristianCristian
169k53334253
169k53334253
1
@user573536 be aware that usinggetResources().getIdentifier()
in a loop can cause performance to degrade when you have a large number of lookups.
– dave.c
Feb 1 '11 at 16:47
You are right. I recommend that approach only when there's a sequence or order for the resources AND there are a lot of them (creating an array of 50 resources smells).
– Cristian
Feb 1 '11 at 17:03
add a comment |
1
@user573536 be aware that usinggetResources().getIdentifier()
in a loop can cause performance to degrade when you have a large number of lookups.
– dave.c
Feb 1 '11 at 16:47
You are right. I recommend that approach only when there's a sequence or order for the resources AND there are a lot of them (creating an array of 50 resources smells).
– Cristian
Feb 1 '11 at 17:03
1
1
@user573536 be aware that using
getResources().getIdentifier()
in a loop can cause performance to degrade when you have a large number of lookups.– dave.c
Feb 1 '11 at 16:47
@user573536 be aware that using
getResources().getIdentifier()
in a loop can cause performance to degrade when you have a large number of lookups.– dave.c
Feb 1 '11 at 16:47
You are right. I recommend that approach only when there's a sequence or order for the resources AND there are a lot of them (creating an array of 50 resources smells).
– Cristian
Feb 1 '11 at 17:03
You are right. I recommend that approach only when there's a sequence or order for the resources AND there are a lot of them (creating an array of 50 resources smells).
– Cristian
Feb 1 '11 at 17:03
add a comment |
you can Use tag if you want to access.
in onClick
int i=Integer.parseInt(v.getTag);
But you cant access that button like this.
simply create button programatically
by Button b=new Button(this);
add a comment |
you can Use tag if you want to access.
in onClick
int i=Integer.parseInt(v.getTag);
But you cant access that button like this.
simply create button programatically
by Button b=new Button(this);
add a comment |
you can Use tag if you want to access.
in onClick
int i=Integer.parseInt(v.getTag);
But you cant access that button like this.
simply create button programatically
by Button b=new Button(this);
you can Use tag if you want to access.
in onClick
int i=Integer.parseInt(v.getTag);
But you cant access that button like this.
simply create button programatically
by Button b=new Button(this);
edited Mar 10 '16 at 18:51
cricket_007
80k1142110
80k1142110
answered Feb 1 '11 at 16:42
Ganapathy CGanapathy C
4,81053668
4,81053668
add a comment |
add a comment |
create Custom Button in java code rather in Xml as i shown below
Button bs_text= new Button[some_value];
for(int z=0;z<some_value;z++)
{
try
{
bs_text[z] = (Button) new Button(this);
}
catch(ArrayIndexOutOfBoundsException e)
{
Log.d("ArrayIndexOutOfBoundsException",e.toString());
}
}
add a comment |
create Custom Button in java code rather in Xml as i shown below
Button bs_text= new Button[some_value];
for(int z=0;z<some_value;z++)
{
try
{
bs_text[z] = (Button) new Button(this);
}
catch(ArrayIndexOutOfBoundsException e)
{
Log.d("ArrayIndexOutOfBoundsException",e.toString());
}
}
add a comment |
create Custom Button in java code rather in Xml as i shown below
Button bs_text= new Button[some_value];
for(int z=0;z<some_value;z++)
{
try
{
bs_text[z] = (Button) new Button(this);
}
catch(ArrayIndexOutOfBoundsException e)
{
Log.d("ArrayIndexOutOfBoundsException",e.toString());
}
}
create Custom Button in java code rather in Xml as i shown below
Button bs_text= new Button[some_value];
for(int z=0;z<some_value;z++)
{
try
{
bs_text[z] = (Button) new Button(this);
}
catch(ArrayIndexOutOfBoundsException e)
{
Log.d("ArrayIndexOutOfBoundsException",e.toString());
}
}
answered Feb 1 '11 at 16:43


Sankar GaneshSankar Ganesh
10.2k114985
10.2k114985
add a comment |
add a comment |
If your top level view only has those button views as children, you could do
for (int i = 0 ; i < yourView.getChildCount(); i++) {
Button b = (Button) yourView.getChildAt(i);
b.setOnClickListener(xxxx);
}
If there are more views present you'd need to check if the selected one is one of your buttons.
do you know how the performance compares with the other suggested methods? I'd assume that it was slightly slower than an array of ID's, but I'd be interested to know how it compares withgetResources().getIdentifier()
.
– dave.c
Feb 1 '11 at 16:58
No sorry no idea. A view knows his children, so I don't think it is too bad.
– Heiko Rupp
Feb 1 '11 at 21:26
add a comment |
If your top level view only has those button views as children, you could do
for (int i = 0 ; i < yourView.getChildCount(); i++) {
Button b = (Button) yourView.getChildAt(i);
b.setOnClickListener(xxxx);
}
If there are more views present you'd need to check if the selected one is one of your buttons.
do you know how the performance compares with the other suggested methods? I'd assume that it was slightly slower than an array of ID's, but I'd be interested to know how it compares withgetResources().getIdentifier()
.
– dave.c
Feb 1 '11 at 16:58
No sorry no idea. A view knows his children, so I don't think it is too bad.
– Heiko Rupp
Feb 1 '11 at 21:26
add a comment |
If your top level view only has those button views as children, you could do
for (int i = 0 ; i < yourView.getChildCount(); i++) {
Button b = (Button) yourView.getChildAt(i);
b.setOnClickListener(xxxx);
}
If there are more views present you'd need to check if the selected one is one of your buttons.
If your top level view only has those button views as children, you could do
for (int i = 0 ; i < yourView.getChildCount(); i++) {
Button b = (Button) yourView.getChildAt(i);
b.setOnClickListener(xxxx);
}
If there are more views present you'd need to check if the selected one is one of your buttons.
answered Feb 1 '11 at 16:55
Heiko RuppHeiko Rupp
22.3k1170113
22.3k1170113
do you know how the performance compares with the other suggested methods? I'd assume that it was slightly slower than an array of ID's, but I'd be interested to know how it compares withgetResources().getIdentifier()
.
– dave.c
Feb 1 '11 at 16:58
No sorry no idea. A view knows his children, so I don't think it is too bad.
– Heiko Rupp
Feb 1 '11 at 21:26
add a comment |
do you know how the performance compares with the other suggested methods? I'd assume that it was slightly slower than an array of ID's, but I'd be interested to know how it compares withgetResources().getIdentifier()
.
– dave.c
Feb 1 '11 at 16:58
No sorry no idea. A view knows his children, so I don't think it is too bad.
– Heiko Rupp
Feb 1 '11 at 21:26
do you know how the performance compares with the other suggested methods? I'd assume that it was slightly slower than an array of ID's, but I'd be interested to know how it compares with
getResources().getIdentifier()
.– dave.c
Feb 1 '11 at 16:58
do you know how the performance compares with the other suggested methods? I'd assume that it was slightly slower than an array of ID's, but I'd be interested to know how it compares with
getResources().getIdentifier()
.– dave.c
Feb 1 '11 at 16:58
No sorry no idea. A view knows his children, so I don't think it is too bad.
– Heiko Rupp
Feb 1 '11 at 21:26
No sorry no idea. A view knows his children, so I don't think it is too bad.
– Heiko Rupp
Feb 1 '11 at 21:26
add a comment |
If for some reason you can't use the getIdentifier()
function and/or you know the possible id's beforehand, you could use a switch.
int id = 0;
switch(name) {
case "x":
id = R.id.x;
break;
etc.etc.
}
String value = findViewById(id);
add a comment |
If for some reason you can't use the getIdentifier()
function and/or you know the possible id's beforehand, you could use a switch.
int id = 0;
switch(name) {
case "x":
id = R.id.x;
break;
etc.etc.
}
String value = findViewById(id);
add a comment |
If for some reason you can't use the getIdentifier()
function and/or you know the possible id's beforehand, you could use a switch.
int id = 0;
switch(name) {
case "x":
id = R.id.x;
break;
etc.etc.
}
String value = findViewById(id);
If for some reason you can't use the getIdentifier()
function and/or you know the possible id's beforehand, you could use a switch.
int id = 0;
switch(name) {
case "x":
id = R.id.x;
break;
etc.etc.
}
String value = findViewById(id);
answered Apr 17 '18 at 23:08
B.CakirB.Cakir
118112
118112
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4865244%2fandroid-using-findviewbyid-with-a-string-in-a-loop%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown