- 我们可以在Drawable文件夹下以XML的形式自定义组件的背景,而在自定义背景的时候我们有时候需要动态修改我们自定义背景的颜色等属性。
- 这里我就以动态修改背景颜色为列子,其他大致和修改颜色一样
- 这里不多废话直接
首先看一下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中自定义的背景