如何在Drawable xml中的运行时更改形状纯色

时间:2015-02-01 15:45:26

标签: android xml layer-list

我想用实际的可绘制方式更改纯色。

源:

link

@ drawable / rightmenu_categories_title:

<item
    android:id="@+id/drawable_main_title_details_content_an_item"
    >
    <shape android:shape="rectangle">

        <solid android:color="#f4262b"/>
        <corners android:topLeftRadius="4dp"/>

    </shape>

</item>

我的布局:

<RelativeLayout
    android:id="@+id/lay_rel_title_categories_rightmenucontents" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"

    >

    <TextView
        android:id="@+id/txt_view_title_detalis_content_an_item" 
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:textSize="16sp"
        android:gravity="center"
        android:text="@string/str_title_categories_rightmenu"
        android:background="@drawable/rightmenu_categories_title"
        />

</RelativeLayout> 

private void setColorOnTitleDetailContentAnItem(int which){
    View v = getActivity().findViewById(R.id.txt_view_title_detalis_content_an_item);

    LayerDrawable bgDrawable = (LayerDrawable)v.getBackground();
    final GradientDrawable shape = (GradientDrawable)  bgDrawable.findDrawableByLayerId(R.id.drawable_main_title_details_content_an_item);
    shape.setColor(Color.BLACK);
}

但我得到了以下错误:

> Caused by: java.lang.NullPointerException 02-01 19:10:05.326:
> E/AndroidRuntime(23755):  at
> ....ContentAnItem.setColorOnTitleDetailContentAnItem(ContentAnItem.java:241)
> 02-01 19:10:05.326: E/AndroidRuntime(23755):  at
> ....ContentAnItem.findViewsById(ContentAnItem.java:227)

在241行:

LayerDrawable bgDrawable = (LayerDrawable)v.getBackground();

在227行,我的函数被调用。


已解决:

片段类中的

我必须使用rootView:

  View v = rootView.findViewById(R.id.txt_view_title_detalis_content_an_item);

0 个答案:

没有答案