0

我在RelativeLayout 中有一个手动创建的TextView 数组。所有显示完美,除了:onclicklistener not work 代码:

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

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

4

2 回答 2

2

在设置之前初始化你的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);
}
于 2016-11-30T18:18:51.887 回答
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
    }
}
于 2016-11-30T18:48:32.957 回答