OnClickListener和表格布局 [英] OnClickListener and Table Layout

查看:113
本文介绍了OnClickListener和表格布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个布局的Activity,都在R.layout.main中实现。第一个是应用程序主屏幕的相对布局,另一个是表格布局,持有一种首选项屏幕。通常,第一个设置为可见,第二个设置为可见。通过单击按钮,我使相对布局消失,并且表格布局可见。
这里开始我的问题,我想将OnClickListener设置为该表布局(实际上是一个按钮数组)。
我试过类似的东西:

I have an Activity with two layouts, both implemented 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 an array of buttons). I tried something 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.

推荐答案

它无法正常工作,因为您首先尝试将TableLayout转换为按钮...
if你的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复制到Activity本身......

and let your activity implement OnClickListener. Just copy your Existing onClick into Activity itself...

这篇关于OnClickListener和表格布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆