【问题标题】:Android app widgets background shape change color opacity programmaticallyAndroid应用小部件背景形状以编程方式更改颜色不透明度
【发布时间】:2019-02-12 15:58:57
【问题描述】:

我开发了一个带有圆角的应用小部件。我基本上已经为应用小部件布局的根设置了一个可绘制的背景。

现在我正在尝试在不丢失圆角的情况下更改其背景不透明度。

我知道RemoteViews 非常有限。

现在我正在使用这个代码:views.setInt(R.id.root_layout_widget, "setBackgroundColor", ColorUtils.setAlphaComponent(Color.WHITE, opacity))

但是这样我就失去了圆角。如果我不使用RemoteViews,我会获取元素的背景并设置它的alpha。

我的根元素是一个线性布局,我的背景可绘制如下:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@android:color/white" />
    <corners android:radius="2dp" />
</shape>

你知道有什么方法吗?谢谢

【问题讨论】:

    标签: android android-appwidget remoteview appwidgetprovider


    【解决方案1】:

    为了解决这个问题,我从根 LinearLayout 中删除了背景,并将 ShapeDrawable 放置到 ImageView 并重新排列了我的布局,如下所示:

    之前:

    <LinearLayout
      android:background="@drawable/round_corners">
        .....
        .....
    </LinearLayout>
    

    之后:

    <FrameLayout>
        <ImageView
            android:id="@+id/background"
            android:src="@drawable/round_corners"/>
        <LinearLayout>
            .....
            .....
        </LinearLayout>
    </FrameLayout>
    

    并在不丢失圆角的情况下更改背景不透明度:

    remoteViews.setInt(R.id.background, "setImageAlpha", alpha)
    

    【讨论】:

      【解决方案2】:

      你可以试试这段代码

      int transparency = 192;(the amount of opacity level you want to give)
      
      views.setInt(R.id.root_layout_widget, "setBackgroundColor", transparency);
      

      代替

      views.setInt(R.id.root_layout_widget, "setBackgroundColor", ColorUtils.setAlphaComponent(Color.WHITE, opacity))
      

      【讨论】:

      • 不,这不起作用。如果有帮助,我编辑了帖子。
      【解决方案3】:

      当您设置背景颜色时,您将替换现有的可绘制对象,有点烦人。我建议考虑在背景视图上设置色调,您可能会发现这个答案很有帮助:How to set tint for an image view programmatically in android?

      【讨论】:

        猜你喜欢
        • 2012-06-08
        • 1970-01-01
        • 1970-01-01
        • 2011-07-13
        • 2014-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-29
        相关资源
        最近更新 更多