Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

java - Android RemoteView set StateListDrawable programmatically

I have a Widget for my Android App. On this Widget there is a button. The user can freely choose the color of the button. So I also have to set the colors for the different button states dynamically.

Normally, I would do something like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/colorButtonRedTransparentPressed"
        android:state_pressed="true" />
    <item android:drawable="@color/colorButtonRedTransparentPressed"
        android:state_focused="true" />
    <item android:drawable="@color/colorButtonRedTransparentNotPressed" />
</selector>

As mentioned, I have to do this dynamically because the user is free to choose the color:

  StateListDrawable drawable = new StateListDrawable();
  drawable.addState(new int[] {}, new ColorDrawable(Color.parseColor(customButton.getColorHex())));
  drawable.addState(new int[] { android.R.attr.state_pressed }, new ColorDrawable(Color.parseColor("#0000")));

The challenge:

The button is on a Widget. So i cannot just simply call:

myButton.setBackground(drawable);

I need to call something like this:

remoteView.setInt(R.id.button_fixedvalue, "setBackground", drawable)

But the function expects an integer and I don't have one.

Does anyone have a different approach?

question from:https://stackoverflow.com/questions/65927525/android-remoteview-set-statelistdrawable-programmatically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Option 1

If there is a limited number of colors that the user can choose from, you could create a selector resource for each color option and then use the `setInt()` method to assign the resource ID that corresponds to the selected color.

Option 2

If by "freely choose" you mean that the user can select any possible color - or at least from a very large number - option 1 won't work of course. Depending on what your drawable exactly looks like, you could try this instead:
  1. Create only a single selector resource.
  2. Use an ImageView for your button.
  3. Apply the color as a tint to the ImageView using the ImageView.setColorFilter() method. That would look something like this:
remoteView.setInt(R.id.button_id, "setColorFilter", Color.parseColor("#0000"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...