我已经研究并在android中创建了一些应用程序小部件。因此,我有一个小部件,其中有6个图像视图,当用户单击其中的一个时,该小部件将启动应用程序。

问题是因为用户没有反馈他的触摸成功(我的意思是,视图没有着色,因为没有像其他人一样的onTouchListener)。

我看到许多可以在用户触摸时着色的小部件,但我不能做到这一点(在远程视图中,我无法直接通过视图获得访问权限)!我该怎么做?

最佳答案

您可以通过如下创建自定义可绘制对象并将其设置为ImageView来实现。当用户触摸ImageView时,显示不同的颜色。

widget_item_image.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:drawable="@color/black_overlay"
    android:state_pressed="true"/>
 <item android:drawable="@color/maroon" android:state_enabled="true"/>
</selector>


widget_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="100dp"
  android:background="@color/white">

<ImageView
  android:id="@+id/imageView1"
  android:layout_width="200dp"
  android:layout_height="60dp"
  android:src="@drawable/widget_item_image"
  android:scaleType="fitXY"
  android:layout_margin="10dp"/>
</LinearLayout>


现在,您的窗口小部件提供程序onUpdate()应该将窗口小部件布局设置为远程视图,并向ImageView添加点击意图以开始活动

Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,0);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
remoteViews.setOnClickPendingIntent(R.id.imageView1,pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);


希望这可以帮助。

10-07 12:05
查看更多