项目——单击事件

这里给大家说一下常用的三种点击事件:


页面代码

页面布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/bt_one"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="第一种点击事件" />
    <Button
        android:id="@+id/bt_two"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="第二种点击事件" />
    <Button
        android:id="@+id/bt_three"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="dianji"
        android:text="第三种点击事件" />
</LinearLayout>

页面布局
这里写图片描述

java代码

package com.xiangmu;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
    private Button bt_1;
    private Button bt_2;
    private Button bt_3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //第一种点击事件
        //获取控件
        bt_1 = findViewById(R.id.bt_one);
        //获取点击事件
        bt_1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, "第一种点击事件", 0).show();
            }
        });
        //第二种点击事件
        //获取控件
        bt_2 = findViewById(R.id.bt_two);
        //获取点击事件
        bt_2.setOnClickListener(this);
    }
    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Toast.makeText(MainActivity.this, "第二种点击事件", 0).show();
    } 
    //第三种点击事件
    public void dianji(View v) {
        Toast.makeText(MainActivity.this, "第三种点击事件", 0).show();
    }
}

**

- 注意:结果就是点击出现一个吐司

**

猜你喜欢

转载自blog.csdn.net/qq_40477146/article/details/80457015