【问题标题】:How can I add onclicklistener for each cell of a table?如何为表格的每个单元格添加 onclicklistener?
【发布时间】:2013-10-09 09:24:42
【问题描述】:

我有一个带有表格的 TableLayout。如何为该表格的每个单元格设置onClicklisteners

我还没有找到任何合适的解决方案。

【问题讨论】:

    标签: android android-layout onclicklistener android-tablelayout


    【解决方案1】:

    试试这个代码,

    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);
                }
            }
        }
    

    【讨论】:

    • 为什么要使用按钮?
    • @KovácsÁkos 无需用于您的应用程序。
    • 我今天遇到了同样的问题,这就是治疗方法。非常感谢您提供这个很棒的解决方案。我投票赞成有用的答案。 :)
    • @shijuB 你能解释一下它是如何工作的吗?它有效,但我试图找到它是如何工作的,但我找不到令人满意的答案。谢谢。
    【解决方案2】:

    我相信您必须为包含您的 TableLayout 的每个 View 对象设置点击侦听器。

    【讨论】:

    • 我有一个 10x10 的表格,所以有 100 个单元格。
    【解决方案3】:

    如果你有表格行,试试这样:

    tableRow.setClickable(true);
    tableRow.setOnClickListener(onClickListener);
    

    否则,您需要使用setTag()getTag() 使用customAdapter 为tableLayout 单元格。您可以从here 了解如何在适配器中使用setTag()/getTag()

    您可以在适配器内部进行跟踪:

    @Override
    public View getView(final int row, final int column, View converView, ViewGroup parent) {
        if (converView == null) {
            converView = inflater.inflate(getLayoutResource(row, column), parent, false);
            if (row == -1){
                converView.setId(column+2);         // assign new id to the cell view
                setHeaderId(column);        // store that view id in the header array
            }  
        }
    
        converView.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View v) {
    
                   // perform what you want
    
            }
        });     
    
        return converView;
    }
    

    【讨论】:

    • 但是如何识别一行中的单元格呢?
    猜你喜欢
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多