Java onclick侦听器和表布局
我有一个包含两个布局的活动,都在R.layout.main中实现。第一个是与应用程序主屏幕的相对布局,另一个是表格布局,包含一种首选项屏幕。通常,第一个设置为可见,第二个设置为消失。通过单击按钮,我使相对布局消失,表格布局可见。 这里开始我的问题,我想为这个表布局(实际上是一个按钮数组)设置一个OnClickListener。 我试过这样的方法:Java onclick侦听器和表布局,java,android,arrays,button,onclicklistener,Java,Android,Arrays,Button,Onclicklistener,我有一个包含两个布局的活动,都在R.layout.main中实现。第一个是与应用程序主屏幕的相对布局,另一个是表格布局,包含一种首选项屏幕。通常,第一个设置为可见,第二个设置为消失。通过单击按钮,我使相对布局消失,表格布局可见。 这里开始我的问题,我想为这个表布局(实际上是一个按钮数组)设置一个OnClickListener。 我试过这样的方法: final TableLayout table = (TableLayout)findViewById(R.id.tab); table.se
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);
}
}
}
}
TableLayourRootLayout=findView。。。。
int count=yourRootLayout.getChildCount();
for(int i=0;i
并让您的活动实现OnClickListener。只需将您现有的onClick复制到活动本身…谢谢您的回答。事实上,我可能说得有点不清楚。我有一个由5行组成的表格布局,每行4个按钮。最终它是一个只包含按钮的数组,但是,您的方法将表行作为子行返回,因此OnClickListener仍然不能正常工作。你有什么改进的办法吗?提前谢谢。它工作得很好。我想我自己再过一个星期也不会明白了。多谢各位。