Android的 - OnClickListener和表布局 [英] Android - OnClickListener and Table Layout

查看:101
本文介绍了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();

        }
    });

显然,这是行不通的。 我是很新的Andr​​oid的编程,我一直在寻找一个合适的解决方案,全日没有任何结果。 先谢谢了。

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...

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

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