Android的 - OnClickListener和表布局
我有两个布局,无论implementd在R.layout.main的活动。第一个是与应用程序的主屏幕上一个相对布局,另一个是一个表布局,抱着一种preferences屏幕。正常情况下,第一个被设置为可见的,而第二个到不见了。通过点击一个按钮,我做了相对布局走了,和表布局可见。 在这里开始我的问题,我想设置一个OnClickListener到表布局(这实际上是按钮的排列)。 我试过某事喜欢:
I have an Activity with two layouts, both implementd in R.layout.main. The first one is a Relative Layout with the app's main screen, and the other is a Table Layout, holding a kind of Preferences Screen. Normally, the first one is set to visible, and the second one to gone. By clicking a button I make the Relative Layout gone, and the Table Layout visible. And here starts my problem, I wanted to set a OnClickListener to that Table Layout (which is actually a array of buttons). I tried sth like:
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的编程,我一直在寻找一个合适的解决方案,全日没有任何结果。 先谢谢了。
Obviously, it doesn't work. I'm quite new to Android programming, and I've been looking for a suitable solution for the whole day without any results. Thanks in advance.
这可能不行,因为你是第一次尝试投TableLayout到一个按钮... 如果您TableLayout只包含按钮,你可以这样做:
It couldn't work because you are first trying to cast a TableLayout to a button... if your TableLayout is only containing buttons you could do something like:
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到活动本身...
and let your activity implement OnClickListener. Just copy your Existing onClick into Activity itself...