Android 以编程方式配置小部件面

Android 以编程方式配置小部件面,android,configuration,interface,widget,Android,Configuration,Interface,Widget,如何以编程方式配置小部件面?我创建了一个小部件: 布局: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" androi

如何以编程方式配置小部件面?我创建了一个小部件:

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:layout_margin="2dip"
    android:background="@drawable/widget"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dip"
        android:layout_marginRight="3dip"
        android:layout_marginTop="3dip"
        tools:ignore="UseCompoundDrawables" >

        <TextView
            android:id="@+id/widget_title"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/app_name"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <ImageView
            android:id="@+id/edit_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="1dip"
            android:contentDescription="@string/edit"
            android:src="@drawable/widget_edit" />
    </LinearLayout>

    <TextView
        android:id="@+id/widget_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="4dip"
        android:layout_marginRight="4dip" />

</LinearLayout>

形状(@drawable/widget):



我需要在配置活动中设置文本视图的背景色、背景透明度、边框颜色和字体大小/颜色。但是如何获取TextView对象以及如何访问形状属性?

与正常活动不同,在小部件中,您不能使用
findViewById
直接实例化
TextView

您需要实例化一个
remoteview
对象,并将包名作为参数传递:

RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_widget);
remoteViews.setInt(R.id.widget_title, "setBackgroundResource", android.R.color.white);
然后使用
remoteview
对象的
setInt
方法,以
TextView
的原始函数作为参数,影响
TextView

RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_widget);
remoteViews.setInt(R.id.widget_title, "setBackgroundResource", android.R.color.white);
最后,更新小部件:

ComponentName thisWidget = new ComponentName(context, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, remoteViews);
您可以使用该方法尝试其他组合
public void setInt(int-viewId,String-methodName,int-value)
并将原始的
methodName
作为参数传递,但由于某些原因,小部件上下文中不允许所有内容。试试看