0

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

布局:

<?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):

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <stroke
        android:width="1dp"
        android:color="#FFFFFFFF" />

    <solid android:color="#00000000"/>

    <corners
        android:bottomLeftRadius="7dp"
        android:bottomRightRadius="7dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />

</shape>

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

4

1 回答 1

1

与普通活动不同,在小部件中,您不能直接实例化 a TextViewwith findViewById

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

RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_widget);

然后以原来的函数作为参数影响对象的TextView使用方法:setIntremoteViewsTextView

remoteViews.setInt(R.id.widget_title, "setBackgroundResource", android.R.color.white);

最后,更新 Widget:

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作为参数传递,但由于某种原因,Widget 上下文中并非所有内容都允许。试试看!

于 2013-03-12T14:35:05.290 回答