简体   繁体   中英

Why won't this change the color?

I asked a question before on how I can change the color of the default android drawable star into yellow, rather than white, and I got an answer to do this:

 Drawable drawable = getResources().getDrawable(android.R.drawable.btn_star);
        drawable.setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);

Here is my star:

    android:onClick = "star"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentTop="true"
    android:background="@android:drawable/btn_star"

/>

But, the star is still white (Image below) Why wasn't the setColorFilter working? The star's edges turn yellow when I click on it... How can I keep the star yellow using the android's provided star drawable?

在此处输入图片说明

Change your onclick listener to this

  public void star (View object){


    object.getBackground().setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);
}

I believe android creates a specific drawable object for each widget that uses a drawable.

If you ask why do get the edge glow yellow, simply it's the default theme for this drawable, if you removed your code it will still glow yellow at edges.

If you want to change it on loading, you can write the code in onCreate() if you are using activity

View object = findViewById(R.id.object_id);

object.getBackground().setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);

You are doing it all wrong. You have set the background in xml. Than you are creating a Drawable object in java and apply color filter on it. Those two are totally different with no connection at all.

Do this : (I am assuming that you are using a ImageButton in layout xml)

<ImageButton
    android:id="@+id/imageButton"
    android:onClick="star"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentTop="true" />

Now in your activity class's onCreate() method do :

ImageButton btnStar = (ImageButton) findViewById(R.id.imageButton);
Drawable drawable = getResources().getDrawable(android.R.drawable.btn_star);
drawable.setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);
btnStar.setBackground(drawable);

This will set the modified drawable as your ImageButton's Background. You can apply same logic for Button, ImageView, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM