动态改变Drawable中我们自定义背景的颜色并设置颜色以16进制进行设置

  1. 我们可以在Drawable文件夹下以XML的形式自定义组件的背景,而在自定义背景的时候我们有时候需要动态修改我们自定义背景的颜色等属性。
  2. 这里我就以动态修改背景颜色为列子,其他大致和修改颜色一样
  3. 这里不多废话直接
    首先看一下activity中怎样修改
public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Button button = (Button) findViewById(R.id.button);
        GradientDrawable gradientDrawable = (GradientDrawable) button.getBackground();
        gradientDrawable.setColor(Color.parseColor("#6ABD20"));
    }
}

首先我们先获取到Drawable对象,然后用Drawable进行设置颜色
Color.parseColor(“#6ABD20”)就是一16进制的形式进行设置颜色
接着贴出Drawable中的代码

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="5dp"/>
    <solid android:color="#FFB22727"/>
</shape>

shape代表矩形同时也会有其他形状这里就不多说了
corners代表矩形的四个角的角度
solid 代表填充颜色

Drawable的使用

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.as.myview.Main2Activity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_centerInParent="true"
        android:text="下一个"
        android:background="@drawable/activity_bg"
        />
</RelativeLayout>

通过background就可以直接使用在Drawable中自定义的背景

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值