【问题标题】:How to set background color for an item programmatically in listview in a widget?如何在小部件的列表视图中以编程方式为项目设置背景颜色?
【发布时间】:2019-07-11 09:28:37
【问题描述】:

我按照github上的示例代码做了一个WidgetLoremWidget

我想为每个项目设置不同的背景颜色(不是随机的)。 我想在该行下方设置背景颜色:

row.setTextViewText(R.id.widget_row_title, items[position].title)
// I want to do something similar like:
// row.findViewById<LinearLayout>(R.id.widget_row_root).setBackgroundColor = ...

我要设置的颜色是"#e57373"这样的字符串形式

----编辑----

为了更好地理解问题,在数据提供者类中为小部件设置背景颜色没有这样的方法:

public class LoremViewsFactory implements RemoteViewsService.RemoteViewsFactory {
    @Override
    public RemoteViews getViewAt(int position) {
        // no method available for setting background color

【问题讨论】:

标签: android android-widget


【解决方案1】:

请检查这个更新的答案:-

在定义主要小部件布局的布局中,我必须添加以下内容:android:id="@+id/LineaRLayout1"

然后在 AppWidgetProvider 中,onUpdate 最终看起来像这样,我在这里真正展示的是我如何更改颜色

只需将项目的 ID 替换为您的项目 ID。

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int N = appWidgetIds.length;

    Log.d(LOG_TAG, "Updating Example Widgets.");

    // Perform this loop procedure for each App Widget that belongs to this
    // provider
    for (int i = 0; i < N; i++) {
        int appWidgetId = appWidgetIds[i];

        // Create an Intent to launch ExampleActivity
        Intent intent = new Intent(context, WidgetActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        // Get the layout for the App Widget and attach an on-click listener
        // to the button
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);

        //try change color here with no luck, I tried activity_main,background, widget1

        views.setInt(R.id.LineaRLayout1, "setBackgroundColor", Color.GREEN);
        views.setOnClickPendingIntent(R.id.button, pendingIntent);
        // Tell the AppWidgetManager to perform an update on the current app
        // widget
        appWidgetManager.updateAppWidget(appWidgetId, views);

【讨论】:

    【解决方案2】:

    我在onUpdate 方法中这样做

    remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget);
    
    if(/*condition for changing background colour is met*/){
        remoteViews.setInt(R.id.widget_row_title, "setBackgroundColor", R.color.new_colour);
    }else{
        remoteViews.setInt(R.id.widget_row_title, "setBackgroundColor", R.color.default_colour);
    }
    

    【讨论】:

    • 我认为您正在为整个列表设置背景,我想为列表项设置它
    • 我在getViewAt中写了setInt方法,所以不用关心条件...
    猜你喜欢
    • 2019-05-29
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多