文本视图 onclicklistener 不工作

textview onclicklistener not working

我在 RelativeLayout 中有一个手动创建的 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);

什么都没有: - 没有错误 - 没有日志

在设置之前初始化您的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);
}

如果ClickListener会有一些复杂的逻辑,最好将其提取出来单独class(例如内部class)。

// 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
    }
}