android 舍入小部件和控制透明度

nwwlzxa7  于 2023-04-04  发布在  Android
关注(0)|答案(1)|浏览(110)

我需要实现一个小部件的能力,以改变背景颜色和透明度与圆形边缘的增加。
我可以使用Color.argb更改背景的透明度,但如果不使用shape,我就无法添加圆角边缘,在shape中,我无法直接通过代码更改透明度。
现在我进退两难具有圆形边缘但不能使背景透明的窗口小部件,或者具有改变背景透明度能力的没有圆形边缘的窗口小部件。
也许你有一些关于如何实现圆角边缘和改变窗口小部件透明度的技巧?

public class TestWidget extends AppWidgetProvider {
@Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        for (int appWidgetId : appWidgetIds) {
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_test);

            int bg = context.getColor(R.color.black);
            bg = Color.argb(128, Color.red(bg), Color.green(bg), Color.blue(bg));
            views.setInt(R.id.container, "setBackgroundColor",bg);
            
            //or

            views.setInt(R.id.container, "setBackgroundResource",R.drawable.round);
        }
    }
}

round.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#000" />
    <corners android:radius="14dp" />
</shape>
jjhzyzn0

jjhzyzn01#

1.创建两个可绘制资源:一个用于圆角,一个用于具有透明度的纯色。
rounded_corners.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="10dp"/>
</shape>

transparent_background.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#80000000"/>
    <corners android:radius="10dp"/>
</shape>

1.在onUpdate方法中,创建一个LayerDrawable,将这两个可绘制对象组合在一起:
public void onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIds){ for(int appWidgetId:appWidgetIds){ RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.widget_test);

// Create a LayerDrawable that combines the rounded corners and the transparent background
    Drawable[] layers = new Drawable[2];
    layers[0] = context.getResources().getDrawable(R.drawable.rounded_corners);
    layers[1] = context.getResources().getDrawable(R.drawable.transparent_background);
    LayerDrawable layerDrawable = new LayerDrawable(layers);

    // Set the LayerDrawable as the background of the container view
    views.setInt(R.id.container, "setBackground", layerDrawable);
}

}
1.要更改背景的透明度,您可以从LayerDrawable获取Drawable并设置其alpha值:
//从容器视图中获取LayerDrawable layerDrawable =(LayerDrawable)views.getBackground().getDrawable(0);

// Set the alpha value of the second layer (the transparent background)
layerDrawable.getDrawable(1).setAlpha(alphaValue);

1.要更改背景颜色,可以设置实体可绘制对象的颜色:

// Get the LayerDrawable from the container view
LayerDrawable layerDrawable = (LayerDrawable) views.getBackground().getDrawable(0);

// Set the color of the first layer (the rounded corners)
layerDrawable.getDrawable(0).setColorFilter(color, PorterDuff.Mode.SRC_IN);

相关问题