android textview onclicklistener没有给我反馈

ctehm74n  于 2023-05-05  发布在  Android
关注(0)|答案(2)|浏览(206)

我在RelativeLayout中手动创建TextView数组。一切都很完美,除了:验证码:

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

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

qhhrdooz

qhhrdooz1#

启动前初始化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);
}
j9per5c4

j9per5c42#

如果 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
    }
}

相关问题