简体   繁体   English

OnClickListener 和表格布局

[英]OnClickListener and Table Layout

I have an Activity with two layouts, both implemented in R.layout.main.我有两个布局的活动,都在 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).这里开始了我的问题,我想为那个表格布局设置一个 OnClickListener(它实际上是一个按钮数组)。 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();

        }
    });

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.我对 Android 编程很陌生,我整天都在寻找合适的解决方案,但没有任何结果。

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 转换为按钮......如果您的 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);
            }
        }
    }
}

and let your activity implement OnClickListener.并让您的活动实现 OnClickListener。 Just copy your Existing onClick into Activity itself...只需将您现有的 onClick 复制到 Activity 本身...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM