Android: Using findViewById() with a string / in a loop

倾然丶 夕夏残阳落幕 提交于 2019-12-27 10:45:07

问题


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!


回答1:


You should use 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);
   }
}



回答2:


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);
}



回答3:


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



回答4:


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);




回答5:


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());
            }
        }



回答6:


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.




回答7:


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);


来源:https://stackoverflow.com/questions/4865244/android-using-findviewbyid-with-a-string-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!