Android基本控件中的两个按钮控件,Button普通按钮和ImageButton图像按钮
Button简介,Button(按钮)继承自TextView,在Android开发中,Button是常用的控件,用起来也很简单,可以在界面xml描述文档中定义,也可以在程序创建后加入到界面中,其效果都是一样的,不过最好在xml文档中定义,如果要改变界面,直接在xml中修改,不用修改java程序,并且在xml中定义层次分明。
Button基本用法
首先是添加Button控件到xml布局文件中,也可通过程序添加。
在布局文件中设置按钮的一些属性,如位置,宽高,按钮上的字,颜色等。
最重要的就是要给按钮一个id号,这是按钮唯一的标号。
在程序中获得按钮的形式
button = (Button)findViewById(R.id.buttonld);
处理按钮点击
按钮点击有两种处理方法
第一种是通过onClick属性,通过这个属性设置处理点击事件的方法名,在Activity中实现这个方法。
另一种是用事件监听机制的应用形式。
下面通过实例展示Button的常用效果
<?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>
1.给按钮设置点击事件
findViewById(R.id.btn_click_one).setOnclickListener(onClickListener);
点击之后进行Toast提示
private View.OnClickListener onClickListener=new View.OnClickListener() {
@Override
public void onClick(View v){
Toast.makeText(MainActivity.this,"Button点击事件1",Toast.LENGTH_LONG).show();
}
};
2. 在xml布局文件中设置Button的属性,然后在该布局文件对应的Acitivity中实现该方法。需要注意的是这个方法必须符合三个条件:
1).方法的修饰符是 public
2).返回值是 void 类型
3).只有一个参数View,这个View就是被点击的这个控件。