1

我正在开发一个按钮小部件,当用户单击我想更改资源图像的按钮时,它不起作用,有我的代码:

小部件.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="72dp"
            android:layout_height="72dp"
            android:layout_gravity="center" >

        <ImageButton
            android:id="@+id/widgetButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@android:color/transparent"
            android:src="@drawable/android_widget"
            android:clickable="true"
            android:contentDescription="@string/widget_image"
            />

</FrameLayout>

MyWidgetActivity.java :

public class MyWidgetActivity extends Activity implements ExceptionHandler {

    RemoteViews remoteViews;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ... 

        // Get the remoteViews view
        remoteViews = new RemoteViews(this.getPackageName(), R.layout.widget);

        // Change the remoteViews button clicked style
        remoteViews.setInt(R.id.widgetButton, "setImageResource",
                R.drawable.android_widget2);

    }

}

谢谢你。

4

2 回答 2

1

我使用选择器解决了我的问题:

我在可绘制文件夹中添加了这个 widget_selector.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:state_enabled="true"
        android:drawable="@drawable/android_widget2" />
    <item android:state_focused="true" android:state_enabled="true"
        android:drawable="@drawable/android_widget2" />
    <item android:state_enabled="true" android:drawable="@drawable/android_widget" />

</selector>

然后我在我的 ImageButton 背景属性中引用它,如下所示:

android:background="@drawable/widget_selector"

它就像一个魅力,只有 0 行代码!

于 2013-02-20T17:15:24.340 回答
0
// Get the remoteViews view
remoteViews = new RemoteViews(this.getPackageName(), R.layout.widget);
// Change the remoteViews button clicked style
remoteViews.setInt(R.id.widgetButton, "setImageResource", R.drawable.android_widget2);

//......For update AppWidget
appWidgetManager.updateAppWidget(widgetID, remoteViews);
于 2013-02-19T16:16:36.627 回答