动态创建项目的监听器

时间:2012-05-11 15:47:29

标签: android android-widget remoteview

我有家庭scrren小部件,我正在生成一些项目(我有这个项目的布局)小部件并在它们上设置一些监听器。这很简单,就像这样:

RemoteViews currentItem1 = new RemoteViews(context.getPackageName(), R.layout.complex_list_item);
    updateViews.addView(R.id.panelNews, currentItem1);
    Intent intent1 = new Intent(context, ForexWidget.class);
    intent1.setAction(Constants.ACTION_PRESSED_ITEM);
    PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 0, intent1, 0);
    updateViews.setOnClickPendingIntent(R.id.singleLine, pendingIntent1);

    RemoteViews currentItem2 = new RemoteViews(context.getPackageName(), R.layout.complex_list_item);
    updateViews.addView(R.id.panelNews, currentItem2);
    Intent intent2 = new Intent(context, ForexWidget.class);
    intent2.setAction(Constants.ACTION_PRESSED_ITEM);
    PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 0, intent2, 0);
    updateViews.setOnClickPendingIntent(R.id.singleLine, pendingIntent2);

创建项目,添加到窗口小部件,它看起来很棒,但是听众没有按照我想要的方式工作 - 只有第一个按钮的第一个监听器工作,其他人没有。我想它是因为我为两个具有相同id(R.id.singleLine)的按钮注册setOnClickPendingIntent - 但最大的问题是,当我的内部remoteview时,我无法设置按钮的id ...

有没有办法做这样的事情?很多

编辑:这是我的布局项目,我正在尝试生成。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/singleLine"
    android:layout_width="fill_parent"
    android:layout_height="34dp"
    android:clickable="true"
    android:orientation="vertical" >

    <TextView
            android:id="@+id/txtTime"
            android:layout_width="45dp"
            android:layout_height="wrap_content"
            android:paddingRight="5dp"
            android:textSize="@dimen/fontNewsCompact" />

        <TextView
            android:id="@+id/txtCurrency"
            android:layout_width="30dp"
            android:layout_height="wrap_content"
            android:paddingRight="5dp"
            android:textSize="@dimen/fontNewsExtraCompact" />

</LinearLayout>

1 个答案:

答案 0 :(得分:2)

问题是每个意图的动作必须不同,如果你不改变它,它只会采取第一个(或最后一个,取决于你的标志)。

我在类似情况下所做的是为动作提供额外的唯一标识符,例如:

intent1.setAction(Constants.ACTION_PRESSED_ITEM + "-1");
...
intent2.setAction(Constants.ACTION_PRESSED_ITEM + "-2");

然后在ForexWidget类上使用以下内容:

if (intent.getAction().startsWith(Constants.ACTION_PRESSED_ITEM) {

    // your logic here
}

此外,要向具有相同Id的对象添加待处理的意图,您应该转到最深的范围,以便只包含一个具有该Id的项目。这样,意图应按如下方式添加:

currentItem1.setOnClickPendingIntent(R.id.singleLine, pendingIntent1)
...
currentItem2.setOnClickPendingIntent(R.id.singleLine, pendingIntent2)

这样您就可以使用列表项布局