1.创建3种类型的 Button :
1>只有文字的,用 Button 类,如:
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_text" ... />
2>带有图片的,用 ImageButton 类,如:
3>有图片又有文字的,用 Button 类用 android:drawableLeft 属性:<ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/button_icon" ... />
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_text" android:drawableLeft="@drawable/button_icon" ... />
2.处理单击事件:
方法1>在xml文件中添加 android:onClick 属性,其值为处理该事件的方法名。然后在对应的Activity中实现该方法。如:
在xml中添加 Button,
<?xml version="1.0" encoding="utf-8"?> <Button xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/button_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" android:onClick="sendMessage" />
然后在对应的 Activity 中实现:
/** Called when the user touches the button */ public void sendMessage(View view) { // Do something in response to button click }
方法2>使用 OnClickListener :
当运行过程中实例化 Button或者需要在 Fragment 子类中声明点击行为的时候,需要用到 OnClickListener。
要使用OnClickListener,先创建一个View.OnClickListener类,然后调用setOnClickListener方法将其分配给 button。如:
Button button = (Button) findViewById(R.id.button_send); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Do something in response to button click } });
3.Button样式:
1>可以在<application>中声明主题,如:android:theme="@android:style/Theme.Holo"
2>用 android:background 来定制Button的背景。
3>没有边框的Button:
style="?android:attr/borderlessButtonStyle"
4>自定义背景:在xml文件中为图片背景创建一个包含3种状态的状态列表:
①制作分别代表默认,按下,获得焦点3种状态的位图。为保证适合不同尺寸,最好做成Nine-patch图片
②将位图放置在当前项目的 res/drawable/ 目录下
③在 res/drawable/ 目录下新建一个xml文件,如 button_custom.xml:
item的顺序有关,例如上方的代码中,只有当press和focuse都为false时才轮到default<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/button_pressed" android:state_pressed="true" /> <item android:drawable="@drawable/button_focused" android:state_focused="true" /> <item android:drawable="@drawable/button_default" /> </selector>
④将该xml文件添加到该 Button 的 android:background 属性中:
android:background="@drawable/button_custom"