Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the text onClick on a TextView that is created dynamically?

I have this code so far, to create TextViews with the texts from usernames arrayList.

    TextView txt_con = null;

    for(int i=0; i<usernames.size(); i++)
    {
        txt_con = new TextView(this);
        txt_con.setLayoutParams(lparams);
        txt_con.setPadding(0, 30, 0, 0);
        txt_con.setText(usernames.get(i));
        ll_cont.addView(txt_cont);
    }

and the onClickListener

    txt_con.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            @SuppressWarnings("unused")
            TextView t = ((TextView)v);
            String str = t.getText().toString();
        }
    });

But, it only takes the onClick action on the last TextView. How do i get the onClick action in all of the TextViews ?

like image 270
Vlad.mir Avatar asked Feb 10 '23 03:02

Vlad.mir


2 Answers

TextView txt_con = null;

for(int i=0; i<usernames.size(); i++)
{
    txt_con = new TextView(this);
    txt_con.setLayoutParams(lparams);
    txt_con.setPadding(0, 30, 0, 0);
    txt_con.setText(usernames.get(i));
    ll_cont.addView(txt_cont);

    txt_con.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        @SuppressWarnings("unused")

        String str = txt_con.getText().toString();
    }
});
}
like image 53
Sakshi Avatar answered Feb 15 '23 10:02

Sakshi


You are using a single variable for TextViews, and keep overwriting it.

What you should do is create an array of Text Views like this

int textViewCount = usernames.size();
TextView[] textViewArray = new TextView[textViewCount];

for(int i = 0; i<usernames.size(); i++) {
    textViewArray[i] = new TextView(this);
    textViewArray[i].setLayoutParams(lparams);
    textViewArray[i].setPadding(0, 30, 0, 0);
    textViewArray[i].setText(usernames.get(i));
    ll_cont.addView(txt_cont);
}
like image 35
krikara Avatar answered Feb 15 '23 10:02

krikara