通过使用TableLayout
,我创建了一个简单的表,并向表行和行的单个单元格添加了OnClick
个侦听器。但是,触摸任何单元格只会执行单元格侦听器,并且不会调用TableRow
侦听器。
如何只需轻轻一按桌面即可让这两个侦听器执行?
或者对这种情况有什么更好的建议?
代码:
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class PostSampleTable extends TableLayout {
public PostSampleTable(Context context) {
super(context);
super.setLayoutParams( new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT) );
super.setClickable( true );
init();
}
private void init() {
for (int i = 0; i < 39; i++) {
TableRow lineRow = new TableRow( getContext() );
super.addView( lineRow );
addRowListener( lineRow, i);
for (int j = 0; j < 9; j++) {
View cell = createTextView("DATACELLAT_" +i+ "_" +j+ "", 100);
lineRow.addView( cell );
addCellListener( cell, i, j);
}
}
}
private void addRowListener(TableRow lineRow, int i) {
MyRowL mrl = new MyRowL() {
int rowNum = 0;
@Override
public void onClick(View v) {
Log.d("cxc", "CLICKED Line Row [ " +getRowNum()+ "]");
}
@Override
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
@Override
public int getRowNum() {
return this.rowNum;
}
};
mrl.setRowNum( i );
lineRow.setOnClickListener( mrl );
}
private void addCellListener(View cell, int i, int j) {
MyCellL mcl = new MyCellL() {
int rowNum = 0;
int colNum = 0;
@Override
public void onClick(View v) {
Log.d("cxc", "CLICKED the cell [ " +getRowNum()+ ", " + getColNum()+ "]");
}
@Override
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
@Override
public int getRowNum() {
return this.rowNum;
}
@Override
public void setColNum(int colNum) {
this.colNum = colNum;
}
@Override
public int getColNum() {
return this.colNum;
}
};
mcl.setRowNum( i );
mcl.setColNum( j );
cell.setOnClickListener( mcl );
}
private TextView createTextView(String text, int width) {
TextView reply = new TextView( getContext() );
reply.setText(text);
reply.setWidth( width );
return reply ;
}
interface MyRowL extends OnClickListener {
public void setRowNum(int rowNum);
public int getRowNum();
}
interface MyCellL extends MyRowL {
public void setColNum(int colNum);
public int getColNum();
}
}
答案 0 :(得分:0)
一种方法是直接在单元格TableRow
的末尾触发OnClickListener()
onClick()
:
以您的单元格onClick()
为例:
@Override
public void onClick(View v) {
Log.d("cxc", "CLICKED the cell [ " +getRowNum()+ ", " + getColNum()+ "]");
((TableRow)v.getParent()).performClick();
}
如果单击某个单元格,则会调用两个onClickListner()
方法。此外,如果直接点击一行,比如因为它缺少单元格,则只会调用行onClickListener()
。
如果您仅定位API 15以后的设备,还有performClick()
的替代方法,称为callOnClick()
。