通过本节课可以学习到的内容:
实例代码:
运行效果参见本课程示例App:安卓猴Demos
按钮,可以按下它,或者点击,由用户来执行一个动作或者操作。
Button的xml写法:
<Button
android:id="@+id/btn_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:drawableLeft="@mipmap/ic_launcher"
android:onClick="btnClicked"
android:text="安卓猴是Button"
android:textSize="26sp"
/>
上面使用的Button的xml属性介绍:
代表当前Button的位置要水平居中
;
表示当前的Button中文字左边的一个小图标;
点击事件的其中一个写法。
这里用selector选择器来定义Button的样式,实现自定义的点击响应效果。
res
目录下新建一个drawable
文件夹;drawable
文件夹上右击鼠标,选择New
,再选择Drawable Resource file
,弹出对话框,输入文件名字为bg_btn
,如图:
bg_btn.xml
文件,里面的内容为,实现的效果为默认状态下是holo_blue_bright
颜色,按下状态的颜色是holo_red_light
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/holo_red_light" android:state_pressed="true" />
<item android:drawable="@android:color/holo_blue_bright" />
</selector>
其中的item
标签,用来定义Button的不同状态下显示的drawable
,它可以是图片或者颜色值
,关于状态有如下几个:
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 默认时的背景图片-->
<item android:drawable="@drawable/image1" />
<!-- 没有焦点时的背景图片 -->
<item android:state_window_focused="false"
android:drawable="@drawable/image2" />
<!-- 非触摸模式下获得焦点并单击时的背景图片 -->
<item android:state_focused="true" android:state_pressed="true" android:drawable= "@drawable/image3" />
<!-- 触摸模式下单击时的背景图片-->
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/image4" />
<!--选中时的图片背景-->
<item android:state_selected="true" android:drawable="@drawable/image5" />
<!--获得焦点时的图片背景-->
<item android:state_focused="true" android:drawable="@drawable/image6" />
</selector>
<ImageButton
android:onClick="btnClicked"
android:id="@+id/imagebtn"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"
/>
android:src="@mipmap/ic_launcher"
用来设定ImageButton中的图片。这一节课,我们主要学习了Button和Button的样式以及ImageButton的简单用法。