title: Android Button的基本使用
tags: Button,按钮
---
Button(按钮)继承自TextView,在Android开发中,Button是常用的控件,用起来也很简单,你可以在界面xml描述文档中定义,也可以在程序中创建后加入到界面中,其效果都是一样的。不过最好是在xml文档中定义,因为一旦界面要改变是话,直接修改一下xml就行了,不用修改Java程序,并且在xml中定义层次分明,一目了然。
Button 支持的 XML 属性及相关方法
android:clickable |
setClickable(boolean clickable) |
设置是否允许点击。 clickable=true:允许点击 clickable=false:禁止点击 |
android:background |
setBackgroundResource(int resid) |
通过资源文件设置背景色。 resid:资源xml文件ID 按钮默认背景为android.R.drawable.btn_default |
android:text |
setText(CharSequence text) |
设置文字 |
android:textColor |
setTextColor(int color) |
设置文字颜色 |
android:onClick |
setOnClickListener(OnClickListener l) |
设置点击事件 |
实例:Button点击事件写法1、写法2、设置背景图片、设置背景颜色、设置背景shape、V7包按钮样式
我们首先来看一下布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:orientation="vertical">
<Button
android:id="@+id/btn_click_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button点击事件写法1" />
<Button
android:id="@+id/btn_click_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="Button点击事件写法2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="@mipmap/icon_button_bg"
android:padding="10dp"
android:text="Button设置背景图片" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="@android:color/holo_red_dark"
android:padding="10dp"
android:text="Button设置背景颜色" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="@drawable/shape_button_test"
android:padding="10dp"
android:text="Button设置shape" />
<TextView
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:text="V7包按钮样式"
android:textColor="#ffffffff"
android:textSize="20sp" />
</LinearLayout>
布局文件对应的效果图如下:
上面布局文件中定义了6个Button,它们指定的规则如下。
1.给Button指定了android:id="@+id/btn_click_one",在MainActivity.xml根据id进行查找并且设置点击事件。
//给第一个按钮设置点击事件
findViewById(R.id.btn_click_one).setOnClickListener(onClickListener);
点击之后进行Toast提示。
privat