【问题标题】:OnClickListener and Table LayoutOnClickListener 和表格布局
【发布时间】:2011-09-30 00:55:35
【问题描述】:

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

【问题讨论】:

    标签: java android arrays button onclicklistener


    【解决方案1】:

    它无法工作,因为您首先尝试将 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 本身...

    【讨论】:

    • 感谢您的回答。实际上,我可能说得有点不清楚。我有一个由 5 行组成的表格布局,每行有 4 个按钮。最终它是一个仅由按钮组成的数组,但是,您的方法将表行作为子项返回,因此 OnClickListener 仍然无法正常工作。你有什么改进的想法吗?提前致谢。
    • 完美运行。我猜,再过一周我自己也想不通。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 2013-04-24
    • 1970-01-01
    • 2019-05-13
    相关资源
    最近更新 更多