我有一个具有两个布局的 Activity ,均在 R.layout.main 中实现。第一个是应用程序主屏幕的相对布局,另一个是表格布局,包含一种首选项屏幕。通常,第一个设置为可见,第二个设置为消失。通过单击一个按钮,我使相对布局消失,并且表格布局可见。 这开始了我的问题,我想为该表布局(实际上是一个按钮数组)设置一个 OnClickListener。 我试过类似的东西:
final TableLayout table = (TableLayout)findViewById(R.id.tab);
table.setOnClickListener(new OnClickListener(){
public void onClick(View arg){
Button clickedButton = (Button)arg;
String t = (String) clickedButton.getTag();
Toast toast = Toast.makeText(getApplicationContext(),t,Toast.LENGTH_SHORT);
toast.show();
}
});
显然,这是行不通的。 我对Android编程很陌生,我一直在寻找合适的解决方案一整天都没有任何结果。
最佳答案
它无法工作,因为您首先尝试将 TableLayout 转换为按钮... 如果您的 TableLayout 仅包含按钮,您可以执行以下操作:
TableLayout yourRootLayout = findView....
int count = yourRootLayout.getChildCount();
for(int i = 0; i < count; i++){
View v = yourRootLayout.getChildAt(i);
if(v instanceof TableRow){
TableRow row = (TableRow)v;
int rowCount = row.getChildCount();
for (int r = 0; r < rowCount; r++){
View v2 = row.getChildAt(r);
if (v2 instanceof Button){
Button b = (Button)v2;
b.setOnClickListener(this);
}
}
}
}
并让您的 Activity 实现 OnClickListener。只需将现有的 onClick 复制到 Activity 本身...
关于java - OnClickListener 和表格布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6603868/