GitOPEN's Home.

《Monkey Android》第11课Button和ImageButton

Word count: 628 / Reading time: 3 min
2015/12/09 Share

通过本节课可以学习到的内容:

  • Button的用法
  • Button的样式
  • ImageButton的用法
  • 点击事件的写法(之前已经讲过,不知还会否?)

实例代码:

运行效果参见本课程示例App:安卓猴Demos

github地址:https://github.com/opengit/MonkeyAndroid


Button的用法

按钮,可以按下它,或者点击,由用户来执行一个动作或者操作。

Button的xml写法:

1
2
3
4
5
6
7
8
9
10
<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属性介绍:

  • android:layout_gravity=”center_horizontal”

代表当前Button的位置要水平居中

  • android:drawableLeft=”@mipmap/ic_launcher”

表示当前的Button中文字左边的一个小图标;

  • android:onClick=”btnClicked”

点击事件的其中一个写法。

Button的样式

这里用selector选择器来定义Button的样式,实现自定义的点击响应效果。

  1. res目录下新建一个drawable文件夹;
  2. drawable文件夹上右击鼠标,选择New,再选择Drawable Resource file,弹出对话框,输入文件名字为bg_btn,如图:

  3. 打开bg_btn.xml文件,里面的内容为,实现的效果为默认状态下是holo_blue_bright颜色,按下状态的颜色是holo_red_light

1
2
3
4
5
6
7
<?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,它可以是图片或者颜色值,关于状态有如下几个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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的用法

1
2
3
4
5
6
7
8
<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中的图片。

效果Gif

下课

这一节课,我们主要学习了Button和Button的样式以及ImageButton的简单用法。


欣慰帮到你 一杯热咖啡
【奋斗的Coder!】企鹅群
【奋斗的Coder】公众号
CATALOG
  1. 1. Button的用法
  2. 2. Button的样式
  3. 3. ImageButton的用法
  4. 4. 效果Gif
  5. 5. 下课