实际开发中Button往往需要有不同的背景以适应不同的状态。Android提供了selector供开发者设置不同的背景
解决方案:
首先这是一个Button
<Button
android:id="@+id/btn_1"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_margin="20dp"
android:background="@drawable/selector_button_bg"
android:gravity="center"
android:text="点击此处"
android:textColor="@color/white"
android:textSize="20dp" />
其中background为一个drawable资源,Root element为selector
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_button_bg" android:state_pressed="true" />
<item android:drawable="@color/white" android:state_enabled="false"/>
<item android:drawable="@drawable/shape_button_unselect"/>
selector>
如上代码所示,分别设置了被按压,不可用,及常规状态下的drawable
其中shape_button_bg.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="10dp"/>
<gradient
android:angle="180"
android:centerColor="#4FB4EA"
android:endColor="#C291FF"
android:startColor="#5895FF" />
shape>
其中shape_button_unselect.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="10dp" />
<gradient
android:startColor="@color/teal_200"
android:endColor="#5C6BF1"/>
shape>
shape常用方法:
再此继续讲述,shape的常用方法,shape一般可以有以下几种设置
shapeshape可以指定形状,其中常用的是rectangle和oval分别表示矩形和椭圆;
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval/rectangle/line/ring">
size用于指定绘制图形的宽高
<size
android:width="30dp"
android:height="30dp" />
solid用于指定某一颜色
<solid
android:color="@color/blue"/>
corners用于圆角半径,也可以分别对各个角分别设置
<corners
android:radius="10dp" />
<corners
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
gradient设置渐变色,可以设置三色渐变,渐变角度,渐变类型等属性
<gradient
android:angle="90"
android:centerColor="@color/blue"
android:endColor="#5C6BF1"
android:startColor="@color/teal_200"
android:type="linear" />
stroke设置描边颜色及宽度
<stroke
android:color="@color/red"
android:width="1dp" />
举个例子:圆形的button,红色的描边,渐变色填充
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<gradient
android:angle="90"
android:centerColor="@color/blue"
android:endColor="#5C6BF1"
android:startColor="@color/teal_200"
android:type="linear" />
<stroke
android:color="@color/red"
android:width="1dp" />
<size
android:width="100dp"
android:height="100dp"/>
shape>
圆角矩形的button
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
<gradient
android:angle="90"
android:centerColor="@color/blue"
android:endColor="#5C6BF1"
android:startColor="@color/teal_200"
android:type="linear" />
<stroke
android:color="@color/red"
android:width="1dp" />
shape>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)