android shape xml rotated drawable change color programmatically

亡梦爱人 提交于 2019-12-06 14:08:05

This is somewhat tricky and involves a lot of casts:

TextView view = (TextView) findViewById( R.id.my_text_view );

// Get the drawable from the view, if you're using an imageview src
// element you'll go with view.getDrawable()
LayerDrawable layers = (LayerDrawable) view.getBackground();

// Now get your shape by selecting the id
RotateDrawable rotate = (RotateDrawable) layers.findDrawableByLayerId( R.id.shape_id );

// Finally you can access the underlying shape
GradientDrawable drawable = (GradientDrawable) rotate.getDrawable();

// ... and do you fancy things
drawable.setColor( ... );

Forget about XML and do it by code like that:

   TextView txtView = (TextView)findViewById(R.id. headlineSelect_TXT2);
    ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
        @Override
        public Shader resize(int width, int height) {
            LinearGradient lg = new LinearGradient(0, 0, 0, txtView.getHeight(),
                new int[] { 
                    Color.LIGHT_GREEN, 
                    Color.WHITE, 
                    Color.MID_GREEN, 
                    Color.DARK_GREEN },  
                new float[] {
                    0, 0.45f, 0.55f, 1 },
                Shader.TileMode.REPEAT);
             return lg;
        }
    };
    PaintDrawable p = new PaintDrawable();
    p.setShape(new RectShape());
    p.setShaderFactory(sf);
    txtView.setBackgroundDrawable((Drawable)p);

If you have RotateDrawable in your xml file inside res/drawable then you could try the below code to change the color of rotate drawable.

LayerDrawable layers = (LayerDrawable) getResources().getDrawable(R.drawable.triangle);
RotateDrawable rotateShape = (RotateDrawable) (layers.findDrawableByLayerId(R.id.user_color));
GradientDrawable shape = (GradientDrawable) rotateShape.getDrawable();
shape.setColor(Color.parseColor("#FF0000"));
TextView NotchTV = (TextView) view.findViewById(R.id.bubble_notch);
NotchTV.setBackgroundDrawable(layers);

`

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!