设置透明度部件背景

设置透明度部件背景

本文介绍了设置透明度部件背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主屏幕小部件,线性布局。我试图设置阿尔法使用远程视图运行时的背景,但小部件不加载。

I have a homescreen widget, with linear layout. I'm trying to set Alpha for the background during runtime using remote views, but the widget doesn't load.

我用这样的:

remoteView.setFloat(R.id.widget_background, "setAlpha", (float)0.7);

设置背景颜色或文本颜色以同样的方式,作品。
我如何使用远程视图设置背景透明度?

Setting background color or text color the same way, works.How can I set the background transparency using remote views?

推荐答案

我用以下解决方案:

float opacity = 0.3f;           //opacity = 0: fully transparent, opacity = 1: no transparancy
int backgroundColor = 0x000000; //background color (here black)
remoteView.setInt( R.id.loMain, "setBackgroundColor", (int)(opacity * 0xFF) << 24 | backgroundColor);

loMain 是我的窗口小部件的主要布局

loMain is a main layout of my widget

如果小部件的主要布局使用背景形状(例如机器人:背景=@绘制/ shape_transparent),其具有的圆角那么这里是一个更复杂的解决方案:

If the main layout of the widget uses shape background (e.g. android:background="@drawable/shape_transparent") which has rounded corner then here is a more complex solution:

        float transparency = 0.5f;  //0...1
        long colorFilter = 0x01000000L * (long)(255f * transparency);
        try {
            final Method[] declaredMethods = Class.forName("android.widget.RemoteViews").getDeclaredMethods();
            final int len = declaredMethods.length;
            if (len > 0) {
                for (int m=0; m<len; m++ ) {
                    final Method method = declaredMethods[m];
                    if (method.getName().equals("setDrawableParameters")) {
                        method.setAccessible(true);
                        method.invoke(remoteView, R.id.loMain, true, -1, (int)colorFilter, PorterDuff.Mode.DST_OUT, -1);
                        break;
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

您可以通过使用变量的阿尔法并发挥 colorFilter ,以满足您的需求。

You can play with variables alfa and colorFilter to meet your needs.

这篇关于设置透明度部件背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 04:30