android 代码修改shape solid颜色
时间: 2023-09-03 15:13:27 浏览: 171
在 Android 中,除了在 xml 文件中修改 shape 的 solid 颜色,也可以在代码中进行修改。具体方法是通过获取 shape 对应的 GradientDrawable 对象,然后调用其 setSolid() 方法来设置颜色。以下是示例代码:
```java
// 获取 shape 对应的 GradientDrawable 对象
GradientDrawable shape = (GradientDrawable) context.getDrawable(R.drawable.shape);
// 设置 solid 颜色
shape.setSolid(Color.BLUE);
// 将修改后的 shape 应用到指定的 View 上
view.setBackground(shape);
```
其中,R.drawable.shape 表示 shape 的资源 ID,可以根据实际情况进行修改。上述代码中将 solid 颜色设置为蓝色,你也可以根据需要设置其他颜色。最后,通过 setBackground() 方法将修改后的 shape 应用到指定的 View 上即可。
相关问题
android 修改shape solid颜色
要修改 Android 中的 shape 的 solid 颜色,可以在 shape 文件中找到 solid 标签,并修改其对应的颜色值。例如,如果你想将红色改为蓝色,可以将以下代码中的 #FF0000 替换为 #0000FF:
```xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FF0000" />
<stroke android:width="1dp" android:color="#000000" />
</shape>
```
修改后的代码如下:
```xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#0000FF" />
<stroke android:width="1dp" android:color="#000000" />
</shape>
```
这样就将 shape 的 solid 颜色修改为了蓝色。
Android 动态修改shape里面的颜色
你可以使用代码动态修改shape里面的颜色,具体的实现方法如下:
1. 首先,在res/drawable/目录下创建一个shape.xml文件,定义一个矩形:
```
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/shape_color"/>
</shape>
```
2. 在你的布局文件中,将这个shape设置为一个View的背景:
```
<View
android:id="@+id/shape_view"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/shape"/>
```
3. 在代码中,获取这个View的背景Drawable对象,然后通过setColor()方法修改它的颜色:
```
View shapeView = findViewById(R.id.shape_view);
Drawable shapeDrawable = shapeView.getBackground();
shapeDrawable.setColorFilter(getResources().getColor(R.color.new_shape_color), PorterDuff.Mode.SRC_ATOP);
```
这样就可以动态修改shape里面的颜色了。注意,需要在res/values/colors.xml文件中定义你所需要的颜色。
阅读全文
相关推荐
















