本文章主要讲解使用Button的几种使用方式。
首先,在布局文件放置4个按钮
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="first button"
/>
<Button
android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="second button"
/>
<Button
android:id="@+id/btn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="third button"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="four button"
android:onClick="BtnClick"
/>
</LinearLayout>
在这里,我们发现我分别对按钮一二三设置了ID,而对按钮四并没有设置ID,反而增加了一个onClick属性,后面我们将看到其中的区别。
然后,分别对其操作
package com.sl.buttondemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity
{
private Button btn1=null;
private Button btn2=null;
private Button btn3=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn1.setOnClickListener(listener);
btn2.setOnClickListener(listener);
btn3=(Button)findViewById(R.id.btn3);
btn3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
Toast.makeText(MainActivity.this, "哈哈,这是第三个按钮", Toast.LENGTH_SHORT).show();
}
});
}
private OnClickListener listener=new OnClickListener()
{
@Override
public void onClick(View v)
{
Button btn=(Button)v;
switch (btn.getId())
{
case R.id.btn1:
Toast.makeText(MainActivity.this, "你点击了按钮first", Toast.LENGTH_SHORT).show();
break;
case R.id.btn2:
Toast.makeText(MainActivity.this, "你点击了按钮second", Toast.LENGTH_SHORT).show();
break;
}
}
};
public void BtnClick(View view)
{
Toast.makeText(MainActivity.this, "哈哈,你点击了第四个按钮哦!", Toast.LENGTH_SHORT).show();
}
}
按钮一和按钮二统一集中到一个函数中,然后用switch,case区分每一个按钮,并且做不同的操作。
按钮三直接操作。
按钮四没有查找ID,而是直接使用在xml中定义的函数名操作。
一般而言,如果按钮不是很多,可以向按钮三那样的操作,但是如果按钮很多的话,建议使用按钮一按钮二那样操作,这样将按钮操作放置在一个函数中,便于管理。当然,使用按钮四效果也是不错的选择,因为不需要查找ID,可以直接使用函数名。
效果如图
OK,Android之Button控件学习就到这了。