androidandroid-appwidgetremoteviewappwidgetprovider

Android app widgets background shape change color opacity programmatically


I have developed an app widget with round corners. I've basically set a background drawable to the root of the app widget layout.

Now I'm trying to change its background opacity without losing round corners.

I know that RemoteViews are pretty limited.

Right now I'm using this code: views.setInt(R.id.root_layout_widget, "setBackgroundColor", ColorUtils.setAlphaComponent(Color.WHITE, opacity))

But this way I lose rounded corners. If I wasn't using RemoteViews I would get the background of the element and set its alpha.

My root element is a LinearLayout and my background drawable is the following:

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

Do you know of any ways to do it? Thanks


Solution

  • To solve this I removed the background from my root LinearLayout and place the ShapeDrawable to an ImageView and rearranged my layout like this:

    Before:

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

    After:

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

    And to change the background opacity without losing the round corners:

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

    The alpha value should be an integer between 0 and 255 (inclusive).