我在RelativeLayout中有一个manualy createt TextView数组。所有显示完美除外:onclicklistener无法正常工作 代码:
private RelativeLayout mRLMain;
private TextView [] mTV;
private OnClickListener mTextOnClickListener;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRLMain = (RelativeLayout) findViewById(R.id.rlMainGame);
mTV = new TextView[20];
mSqueareLayout = new RelativeLayout.LayoutParams(mSquareWidth,mSquareWidth);
for (i = 0; i < 20; i++) {
mTV [i] = new TextView(MainActivity.this);
mTV [i].setBackgroundColor(Color.RED);
mTV [i].setTextColor(Color.WHITE);
mTV [i].setX(i+100);
mTV [i].setId(i);
mTV [i].setOnClickListener(mTextOnClickListener);
mRLMain.addView(mTV [i], mSqueareLayout);
}
mTextOnClickListener = new OnClickListener() {
@Override
public void onClick(View view) { Log.d("XXX","CLICK"); }
};
}
尝试
mTV [i].setFocusable(false);
mTV [i].setFocusableInTouchMode(false);
mTV [i].setClickable(true);
mTV [i].setDuplicateParentStateEnabled(false);
没有: - 没有错误 - 没有日志
答案 0 :(得分:2)
在stting之前初始化clickListener
。因此,更改订单可以解决您的问题。
for (i = 0; i < 20; i++) {
mTV [i] = new TextView(MainActivity.this);
mTV [i].setBackgroundColor(Color.RED);
mTV [i].setTextColor(Color.WHITE);
mTV [i].setX(i+100);
mTV [i].setId(i);
// Set clickListener
mTV [i].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Log.d("XXX","CLICK");
Toast.makeText(MainActivity.this, "Position "+ i, Toast.LENGTH_LONG).show();
});
mRLMain.addView(mTV [i], mSqueareLayout);
}
答案 1 :(得分:0)
如果 ClickListener 会有一些复杂的逻辑,最好将它提取到单独的类(例如内部类)。
// same top part
for (int i = 0; i < 20; i++){
mTV [i] = new TextView(MainActivity.this);
mTV [i].setBackgroundColor(Color.RED);
mTV [i].setTextColor(Color.WHITE);
mTV [i].setX(i+100);
mTV [i].setId(i);
// main change here
mTV [i].setOnClickListener(new CustomClickListener(i));
mRLMain.addView(mTV [i], mSqueareLayout);
}
}
static class CustomClickListener implements View.OnClickListener {
private int viewId;
// another option is to pass a reference to a view here
// private View view;
// in this case, you should create appropriate constructor
public CustomClickListener(int viewId) {
this.viewId = viewId;
}
@Override
public void onClick(View view) {
Log.d("XXX","Click on view " + viewId);
// some logic on this view
}
}