android 中 setTextColor 方法使用注意事项

来源:互联网 发布:单片机无线抢答器 编辑:程序博客网 时间:2024/06/11 12:39

                  android中TextView动态设置方法setTextColor失效问题的解决之道


      最近在工作中遇见一个奇怪的问题,在布局文件中使用  android:textColor=   可以直接调用资源库的颜色值,或者drawable 中自定义的selector没有任何问题,可是到Java代码中动态设置,就会出现各种问题。
         
      下面看一下,我犯错的案例:
                               
     原来的xml 布局文件:
<LinearLayout
        android:id="@+id/unfinish"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical" >


        <ImageView
            android:id="@+id/image_unfinish"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="6dp"
            android:contentDescription="@null"
            android:paddingTop="8dp"
            android:scaleType="fitCenter"
            android:src= "@drawable/required_course_img_unlearned" />


        <TextView
            android:id="@+id/textview_unfinish"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:text="@string/requiredcourse_gridview1"
            android:textColor="@drawable/required_course_tvw" 
            android:textSize="12sp"/>
    </LinearLayout>


其中 android:textColor="@drawable/required_course_tvw" 是我自定义的selector,如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_selected="false" android:color="@color/requiredcourse_bottom_item_unselected"></item>  
<item android:state_selected="true" android:color="@color/requiredcourse_bottom_item_selected"></item>
</selector>

后来需求要求需要这个TextView需要在代码文件中动态配置
TextView  tvUnfinish;
tvUnfinish=(TextView)getView().findViewById(R.id.textview_unfinish);

tvUnfinish.setTextColor((R.color.requiredcourse_bottom_item_selected)) -------错误1

这样设置后,变色变成非常奇怪的深蓝色,并不是预期达到的红色,通过查阅资料得出,这个方法错误,具体的原因各位前辈在自觉地博客写得非常详细,我就不再赘述了。

对于错误1,我更正了如下:

tvUnfinish.setTextColor(getActivity().getResources().getColor(R.color.requiredcourse_bottom_item_selected));

这样修改后,就达到了设置字体颜色值的目的,但是,下面我据此要达到点击时字体根据我的selector显示的时候,我又犯了第二个错误:

tvUnfinish.setTextColor(getActivity().getResources().getColor(R.drawable.required_course_tvw));--------错误2

结果发现并没有根据我的预期那样变化,相反,字体颜色不变。

这时候比较郁闷,为什么xml中可以这样设置,到了Java中就不起作用了,我想,android的API如今这么成熟,肯定不会犯如此低级的错误,后来在getActivity().getResources()后面的引导的方法中我找打了这个方法getColorStateList(int resid),然后查询了这个方法的API,发现这个方法的作用就是管理color状态变化的方法,如是第二个错误就解决了

tvUnfinish.setTextColor(getActivity().getResources().getColorStateList(R.drawable.required_course_tvw));

至此,我这种技术小白犯的低级错误终于解决了。为了今后不再犯这样的错误,在此就啰嗦的记录下来。

如有不对,恳请各位高人指正,小白献丑了!






    
0 0
原创粉丝点击