Search code examples
javaandroidonclickonclicklistener

Android Studio TextViews onClick all perform the same action, how do I fix it?


I have this function which is supposed to create an array of TextViews with unique ids.

Each TextView is supposed to perform a unique action, however when any one of them is clicked, they perform the function of the last TextView .

(ie, anyone of them appends a 9 to the last TextView the way this i set up) Do you know why it does this, and how I can fix it?

Any help would be greatly appreciated.

//Code:   
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_what_can_imake);

        int textViewCount = 10;

        TextView[] textViewArray = new TextView[textViewCount];
        RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.myLayout);
        for(int i = 0; i < textViewCount; i++) {
            textViewArray[i] = new TextView(this);
            textViewArray[i].setText("Title"+Integer.toString(i));
            textViewArray[i].setPadding(8,8+50*i,8,0);
            textViewArray[i].setId(i);
            LayoutParams myTitleDimensions = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);


            textViewArray[i].setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    int myId = v.getId();
                    ((TextView) v).append(Integer.toString(myId));
                }
            });
            myLayout.addView(textViewArray[i],myTitleDimensions);
        }

    }

Solution

  • You are using different paddingTop to layout your TextViews vertically:

    textViewArray[i].setPadding(8,8+50*i,8,0);
    

    this makes the TextViews visually separate to each other, but in fact they are all overlapped, the 2nd one overlapped the 1st, the 3rd one overlapped the 2nd, etc. At last, the 9th one overlapped all, so no matter which text you clicked, you actually clicked the 9th one.

    To fix this, you should change the way you layout the TextViews.

    For example, use RelativeLayout.addRule(int verb, int anchor):

    RelativeLayout.LayoutParams myTitleDimensions = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    if (i > 0) {
        myTitleDimensions.addRule(RelativeLayout.BELOW, i - 1);
    }
    

    By the way, 0 is not a valid id, so your 1st TextView will be still overlapped by the 2nd one, just change the way to generate ids a little.