簡體   English   中英

Android如何將xml形狀設置為小部件背景?

[英]Android How to set an xml shape as widget background?

如何在Widget中將xml中定義的形狀設置為圖像的背景? 這是我的嘗試:

RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget_layout);

Drawable dr = getResources().getDrawable(R.drawable.widgetshape);  //class cast exception
Bitmap bp = ((BitmapDrawable)dr).getBitmap();
views.setImageViewBitmap(R.id.ImageView01, bp);

這會導致android.graphics.drawable.GradientDrawable類強制轉換異常。

Bitmap icon = BitmapFactory.decodeResource(WidgetConfig.this.getResources(),  R.drawable.widgetshape);
views.setImageViewBitmap(R.id.ImageView01, icon);

這會在awm.updateAppWidget(awID, views);上引發NullPointerException錯誤awm.updateAppWidget(awID, views); 線。

Bitmap bp = ((BitmapDrawable)this.getResources().getDrawable(R.drawable.widgetshape)).getBitmap(); //Class Cast Exception
views.setImageViewBitmap(R.id.ImageView01, bp);

這會導致第一行出現android.graphics.drawable.GradientDrawable類強制轉換異常。

您可以通過調用RemoteViews實例的setInt方法來實現:

views.setInt(R.id.layout, "setBackgroundResource", R.drawable.widgetshape);

為此,必須在小部件布局的View (可能是根視圖)(在xml中)中將@id屬性設置為"layout"

您還可以通過xml定義該視圖的背景,例如:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout" android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/widgetshape">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM