同时监听多个Button事件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.myapplication7777.MainActivity">



    <Button
        android:id="@+id/but1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button1" />

    <Button
        android:id="@+id/but2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button2" />

    <Button
        android:id="@+id/but3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button3"
        android:onClick="Btn3OnClick"/>




</LinearLayout>
package com.example.administrator.myapplication7777;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_main);


        //第一种方法
        Button Btn1=(Button)findViewById(R.id.but1);
         Button Btn2=(Button)findViewById(R.id.but2);
        Button Btn3=(Button)findViewById(R.id.but3);

        Btn1.setOnClickListener(Listener);
        Btn2.setOnClickListener(Listener);
        Btn3.setOnClickListener(Listener);
    }

    private OnClickListener Listener =new OnClickListener() {
        @Override
        public void onClick(View v) {
            Button btn=(Button)v;
            switch (btn.getId())
            {
                case R.id.but1:
                    Toast.makeText(MainActivity.this,"你点击了1按扭",Toast.LENGTH_LONG).show();
                 break;

                case R.id.but2:
                    Toast.makeText(MainActivity.this,"你点击了2按扭",Toast.LENGTH_LONG).show();
                    break;

                case R.id.but3:
                    Toast.makeText(MainActivity.this,"你点击了3按扭",Toast.LENGTH_LONG).show();
                    break;


            }
        }

    };

}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页