Android:在一个循环中使用findViewById()和一个string

我正在制作一个Android应用程序,其中有一个由数百个button组成的视图,每个button都有一个特定的callback。 现在,我想使用循环来设置这些callback,而不必编写数百行代码(针对每个button)。

我的问题是:如何使用findViewById静态不必键入每个buttonID? 这是我想要做的:

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

提前致谢!

你应该使用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); } } 

您可以尝试创build一个int []来保存所有的buttonID,然后遍历它:

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

看看这些答案:

  • Android和得到一个视图与id转换为一个string
  • ImageButtons数组,从variables中分配R.view.id

你可以使用标签,如果你想访问。

onClick

 int i=Integer.parseInt(v.getTag); 

但是你不能像这样访问这个button。

只需编程创buildbutton

Button b=new Button(this);

在Java代码而不是Xml中创build自定义button,如下所示

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

如果您的顶级视图只有这些button视图作为孩子,你可以做

 for (int i = 0 ; i < yourView.getChildCount(); i++) { Button b = (Button) yourView.getChildAt(i); b.setOnClickListener(xxxx); } 

如果还有更多的视图,你需要检查选中的是否是你的button之一。