开发者

Dynamically added rows, setOnClickListener TextView

开发者 https://www.devze.com 2023-02-18 21:00 出处:网络
I have a for loop that each time prints out a row with a TextView within. I want this TextView to be clickable, and when clicked it is supposed to start another activity and send an ID with the Intent

I have a for loop that each time prints out a row with a TextView within. I want this TextView to be clickable, and when clicked it is supposed to start another activity and send an ID with the Intent. But it's this that I can't manage to work. All links shows up nicely in a table and the textviews are clickable, but all links sends me to the next activity with the same ID, the ID of the last link.

Here is a simplified version of the content of the for loop:

TextView title = new TextView(this);
title.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
title.setText(titleLine);
title.setClickable(true);
title.setId(rows);
rows++;

title.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        Intent myIntent = new Intent(a.this, b.class);
        myIntent.putExtra("id", idLine);
        a.this.startActivity(myIntent);
    }
});

contRight.addView(title);

I suppose the problem is that all textViews looks the same, so the last setOnClickListener works on all links. However, I have added开发者_如何学运维 an ID to each title, with this code: title.setId(rows);, so they are all supposed to be unique.

Anybody who can give some help? :) Thanks!


Shouldn't idLine be v.getId()? It's good for this value to be as "fresh" as possible so that you aren't reading an old value: in this case, the value of the last row which had probably been lurking in idLine. Hence, getting the value from the view directly is the safest method.

Also, the "tag" might be a better place to store information than the id. You can access the tag, and indeed store any number of arguments as tags on any view, without changing the id:

title.setTag(rows);

and then later:

intent.putExtra((Integer) v.getTag());

To store multiple objects (with keys) you can use:

title.setTag("rowid", rows);

and then retrieve it using:

intent.putExtra((Integer) v.getTag("rowid"));

and then you could add additional keys if you requirements changed.

In any case, the intention of the tag is to store information for later retrieval, whereas the id is meant to serve as an identifier for finding views in a hierarchy.

0

精彩评论

暂无评论...
验证码 换一张
取 消