gpt4 book ai didi

android - 小部件自定义图标 Android

转载 作者:行者123 更新时间:2023-11-29 23:38:32 26 4
gpt4 key购买 nike

我想为小部件制作自定义图像,我试过了

views.setImageViewResource(R.id.red_button, R.drawable.button_default);

Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.button_default);

views.setImageViewBitmap(R.id.red_button, icon);

但它一直说加载小部件时出现问题,无论我尝试什么,我是否遗漏了什么?有人可以指出我正确的文档/该怎么做吗?编辑:完整的 xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_green_dark"
android:orientation="vertical"
android:padding="@dimen/widget_margin">


<ImageButton
android:id="@+id/red_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Button"
app:srcCompat="@drawable/button_default" />

</LinearLayout>

代码:

public class NewAppWidget extends AppWidgetProvider {

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {

CharSequence widgetText = context.getString(R.string.appwidget_text);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

Intent intent = new Intent(context, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);

views.setOnClickPendingIntent(R.id.red_button, pi);
views.setTextViewText(R.id.red_button, widgetText);

Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.button_default);

views.setImageViewBitmap(R.id.red_button, icon);
//views.setImageViewResource(R.id.red_button, R.drawable.button_default);


// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}

}

@Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created

}

@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}

谢谢!

最佳答案

错误消息(“problem loading widget”)不是由显示可绘制对象的任何问题引起的,它是由于代码中的这一行而显示的:

views.setTextViewText(R.id.red_button, widgetText);

您只能将 setTextViewText(int, CharSequence) 与从 TextView 扩展的 View 的资源 ID 一起使用(根据 docs ,它等同于 TextView.setText(CharSequence) )。

资源 id R.id.red_button 属于 ImageButton,它从 ImageView 而非 TextView 扩展,这就是您收到错误消息的原因。

因此,如果您想显示一些文本,您需要将 Textview 添加到您的应用小部件的布局中。

关于android - 小部件自定义图标 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52045168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com