RemoteViews setInt setImageResource无法在ImageButton中工作

时间:2013-02-19 16:03:44

标签: android widget imagebutton

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

widget.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);

    }

}

谢谢。

2 个答案:

答案 0 :(得分:1)

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

我在drawable文件夹中添加了这个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行代码!

答案 1 :(得分: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);