Android Shape XML以编程方式旋转可绘制更改颜色 [英] android shape xml rotated drawable change color programmatically

查看:363
本文介绍了Android Shape XML以编程方式旋转可绘制更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是三角形的xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/shape_id">
        <rotate
            android:fromDegrees="45"
            android:toDegrees="45"
            android:pivotX="-40%"
            android:pivotY="87%" >
            <shape android:shape="rectangle" >
                <stroke android:width="10dp"/>
            </shape>
        </rotate>
    </item>
</layer-list>

这是textview的背景

And this is a background of a textview

<TextView
    android:id="@+id/headlineSelect_TXT2"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_weight="1"
    android:background="@drawable/category_triangle_shape1"
    android:visibility="invisible" />

我想以编程方式更改形状的颜色.我尝试了这个,但是我得到了空指针异常

And I want to change color of shape programmatically. I tried this but I am getting null pointer exception

LayerDrawable bgDrawable = (LayerDrawable) getActivity()
    .getResources()
    .getDrawable(R.drawable.category_triangle_shape1);
final GradientDrawable shape = (GradientDrawable) bgDrawable
    .findDrawableByLayerId(R.id.shape_id);
shape.setStroke(10,Color.GREEN);

我该怎么做?感谢您的帮助.

How can I do that? Thanks for help.

推荐答案

这有些棘手,涉及很多强制类型转换:

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

这篇关于Android Shape XML以编程方式旋转可绘制更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆