Android Studio中修改TextView背景色后圆形样式失效的问题求助
解决TextView调用setBackgroundColor后圆形样式失效的问题
问题核心:调用setBackgroundColor()会直接替换TextView原有的GradientDrawable背景(也就是你写的circular shape),换成纯色的ColorDrawable,所以圆形样式会丢失,变回方形。
解决方案1:修改原有ShapeDrawable的颜色(推荐)
直接获取TextView当前的背景Drawable,强制转换为GradientDrawable后修改颜色,这样不会替换整个背景,圆形样式得以保留:
TextView light = findViewById(R.id.traffic_light_label); // 获取原背景的GradientDrawable实例 GradientDrawable circularDrawable = (GradientDrawable) light.getBackground(); // 设置新颜色(适配Android 6.0+版本) circularDrawable.setColor(getResources().getColor(R.color.red, getTheme())); // 若兼容低版本(Android 6.0以下),可使用已过时的getColor(int)方法 // circularDrawable.setColor(getResources().getColor(R.color.red));
解决方案2:创建多色Shape资源,切换背景
如果交通灯颜色固定(红、黄、绿),可以分别创建对应颜色的shape资源:
circular_red.xml(红色圆形)circular_yellow.xml(黄色圆形)circular_green.xml(绿色圆形)
每个文件的结构和你原来的circular.xml一致,只修改<solid>标签的颜色值。然后在代码中切换背景:
light.setBackgroundResource(R.drawable.circular_red); // 切换为红色圆形 light.setBackgroundResource(R.drawable.circular_yellow); // 切换为黄色圆形
问题重现的相关代码
你的XML布局:
<TextView android:id="@+id/traffic_light_label" android:layout_width="100dp" android:layout_height="100dp" android:background="@drawable/circular" android:layout_centerVertical="true" android:layout_centerHorizontal="true" />
导致样式失效的代码:
light=findViewById(R.id.traffic_light_label); light.setBackgroundColor(getResources().getColor(R.color.red));
原circular shape资源:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <size android:width="100dp" android:height="100dp"/> <solid android:color="#FF0000"/> </shape>
内容的提问来源于stack exchange,提问作者Aimex
相关产品推荐
相关产品推荐

