【问题标题】:setonclicklistner to dynamically generated array of textviews [duplicate]setonclicklistner 动态生成的文本视图数组[重复]
【发布时间】:2013-03-07 01:23:30
【问题描述】:

我有一个动态生成的文本视图数组

for(int i = 0; i < blog_link_counter; i++) {
textViewArray[i] = new TextView(this);
textViewArray[i].setText(Html.fromHtml(array_blog_text[i]+"<br>"));
textViewArray[i].setId(i);
textViewArray[i].setOnClickListener(this);
((LinearLayout) linearLayout).addView(textViewArray[i]);
}

现在我有一个活动,其中有许多文本视图。我需要将 onclick 侦听器功能添加到所有文本视图。

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/info"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#FFFFFF" />

我在java文件中添加了onclicklistner。之后我实现了onclicklistner接口

public void onClick(View v) {
    // TODO Auto-generated method stub


switch(v.getId())
{
case R.id.    <--  ?
}

}}

我如何匹配它所引用的 Textview id?我的意思是如果 id 是静态的,我可以像 R.id.idfromxmlfile 那样做,但在这种情况下我应该怎么做?

请帮忙

【问题讨论】:

标签: android android-widget textview


【解决方案1】:

您没有使用R.id.xxx,只需使用您在循环中使用的相同数字:

switch(v.getId())
{
case 0:
case 1:
//etc
}

【讨论】:

    【解决方案2】:

    View.setTag() 函数更适合于此。设置标签而不是设置id

    // Use .setTag
    textViewArray[i].setTag(new Integer(i));
    

    然后,您可以通过调用 .getTag() 来检索视图

    Integer tag = (Integer) v.getTag();
    switch(tag)
    {
    case 0:
    case ...:
    case blog_link_counter - 1:
    }
    

    【讨论】:

    • 呃,这样更合适吗?它的作用完全相同,只是它滥用了标签功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多