How can I add onclicklistener for each cell of a table?

╄→гoц情女王★ 提交于 2019-12-12 02:48:48

问题


I have a TableLayout with a table. How can I set onClicklisteners for each cell of this table?

I have not found any proper solution for this problem.


回答1:


Try this code,

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



回答2:


I believe you have to set click listener for every View object incorporating your TableLayout.




回答3:


Try like this if you have the table rows:

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

Otherwise you need to use setTag() and getTag() using customAdapter for tableLayout cell. you can get the idea how to use setTag()/getTag() in adapter from here.

Inside your adapter you can track:

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


来源:https://stackoverflow.com/questions/19267956/how-can-i-add-onclicklistener-for-each-cell-of-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!