常用控件 01 按钮 Button

本文介绍了在Android应用开发中如何创建不同类型的按钮(Button),包括纯文本按钮、带图标的按钮及图文混排的按钮,并详细解释了如何通过XML属性和Java代码处理按钮点击事件,同时还提供了定制按钮样式的具体方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建3种类型的 Button :

1>只有文字的,用 Button 类,如:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    ... />

2>带有图片的,用 ImageButton 类,如:

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/button_icon"
    ... />
3>有图片又有文字的,用 Button 类用 android:drawableLeft 属性:

<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:

<?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>
item的顺序有关,例如上方的代码中,只有当press和focuse都为false时才轮到default

④将该xml文件添加到该 Button 的 android:background 属性中:

android:background="@drawable/button_custom"






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值