S2K S2K - 9 days ago 5
Android Question

textview onclicklistener not working

I've got a manualy createt TextView array in RelativeLayout. All show perfect except: onclicklistener not work
Code:

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].setFocusable(false);
// mTV [i].setFocusableInTouchMode(false);
//mTV [i].setClickable(true);
//mTV [i].setDuplicateParentStateEnabled(false);
mTV [i].setOnClickListener(mTextOnClickListener);
mRLMain.addView(mTV [i], mSqueareLayout);
}
mTextOnClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
Log.d("XXX","CLICK");
}
};

}


Try with

mTV [i].setFocusable(false);
mTV [i].setFocusableInTouchMode(false);
mTV [i].setClickable(true);
mTV [i].setDuplicateParentStateEnabled(false);


And nothing:
- no errors
- no log's

Answer

Don't change x-coordinate of view, if you want to use RelativeLayout then use its properties like left_of, right_of etc. But for now as per your requirement you can simply use LinearLayout(as a parent view instead of RelativeLayout) with Horizontal orientation.

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); // Remove this property
        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);
}