猿问

以编程方式设置android形状颜色

以编程方式设置android形状颜色

我正在编辑以使问题更简单,希望这有助于获得准确的答案。

说我有以下oval形状:

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:angle="270"
           android:color="#FFFF0000"/>
    <stroke android:width="3dp"
            android:color="#FFAA0055"/></shape>

如何在活动类中以编程方式设置颜色?


三国纷争
浏览 476回答 3
3回答

慕沐林林

drawable是一个椭圆形,是ImageView的背景Drawable从imageView使用中获取getBackground():Drawable background = imageView.getBackground();检查通常的嫌疑人:if (background instanceof ShapeDrawable) {&nbsp; &nbsp; // cast to 'ShapeDrawable'&nbsp; &nbsp; ShapeDrawable shapeDrawable = (ShapeDrawable) background;&nbsp; &nbsp; shapeDrawable.getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));} else if (background instanceof GradientDrawable) {&nbsp; &nbsp; // cast to 'GradientDrawable'&nbsp; &nbsp; GradientDrawable gradientDrawable = (GradientDrawable) background;&nbsp; &nbsp; gradientDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));} else if (background instanceof ColorDrawable) {&nbsp; &nbsp; // alpha value may need to be set again after this call&nbsp; &nbsp; ColorDrawable colorDrawable = (ColorDrawable) background;&nbsp; &nbsp; colorDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));}紧凑版:Drawable background = imageView.getBackground();if (background instanceof ShapeDrawable) {&nbsp; &nbsp; ((ShapeDrawable)background).getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));} else if (background instanceof GradientDrawable) {&nbsp; &nbsp; ((GradientDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));} else if (background instanceof ColorDrawable) {&nbsp; &nbsp; ((ColorDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));}请注意,不需要进行空检查。但是,mutate()如果在其他地方使用它们,则应在修改之前使用drawables。(默认情况下,从XML加载的drawable共享相同的状态。)

慕的地6264312

这样做:&nbsp;&nbsp;&nbsp;&nbsp;ImageView&nbsp;imgIcon&nbsp;=&nbsp;findViewById(R.id.imgIcon); &nbsp;&nbsp;&nbsp;&nbsp;GradientDrawable&nbsp;backgroundGradient&nbsp;=&nbsp;(GradientDrawable)imgIcon.getBackground(); &nbsp;&nbsp;&nbsp;&nbsp;backgroundGradient.setColor(getResources().getColor(R.color.yellow));

萧十郎

现在更简单的解决方案是使用您的形状作为背景,然后通过编程方式更改其颜色view.getBackground().setColorFilter(Color.parseColor("#343434"), PorterDuff.Mode.SRC_OVER)编辑:就像评论中正确指出的人一样PorterDuff.Mode.SRC_ATOP,如果您的背景有圆角等,您可能会想要使用。
随时随地看视频慕课网APP

相关分类

Android
我要回答