- 我們可以在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中自定義的背景