2512天 Mr.贰呆

唯一自信的就是自己的人品。
寻求王者玩家一起开黑净化峡谷环境​​

【Android】开发入门:Button控件使用介绍

发布于 / 1906 次围观 / 0 条评论 / Android / 二呆 /

Android上回简单介绍了GridView图像表格控件,接下来会一个接一个的介绍各个控件的使用方法,现在先来说Button控件。

Button控件最为简单,在Android应用中就是一个按钮,并可以进行点击事件处理,用来触发一定的时间或跳转之用。

1、创建视图并放置Button控件(一般用视图模式Graphical Layout即可)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/relative"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="64dp"
        android:layout_marginTop="80dp"
        android:text="第一个按钮" />
</RelativeLayout>
2、创建Activity并声明Button变量

private Button button1;
3、在onCreate方法中显示布局并提取Button控件

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.relative);
        button1=(Button)findViewById(R.id.button1);
    }

4、为Button设置点击监听时间,有2种方法:

方法一、单独设置onClick事件

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "点击了button", 1).show();
            }
        });
方法二、汇总设置onClick事件
button1.setOnClickListener(this);

public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            Toast.makeText(MainActivity.this, "点击了button", 1).show();
            break;
        default:
            break;
        }
    }
5、运行测试
sitemap