Luca
Luca

Reputation: 352

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

Upvotes: 2

Views: 1749

Answers (3)

Luca
Luca

Reputation: 352

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).

Upvotes: 5

ScouseChris
ScouseChris

Reputation: 4397

When you set the background colour you will replace your existing drawable, kind of annoying. I'd suggest looking into setting the tint colour on your background view, you might find this answer helpful: How to set tint for an image view programmatically in android?

Upvotes: 0

Sana
Sana

Reputation: 456

You can try this code

int transparency = 192;(the amount of opacity level you want to give)

views.setInt(R.id.root_layout_widget, "setBackgroundColor", transparency);

in the place of

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

Upvotes: 0

Related Questions