OnClickListener和表格布局

我有一个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); } } } } 

并让您的活动实现OnClickListener。 只需将您的现有onClick复制到Activity本身......