android四种不同的事件实现

EvenActivity.java

package com.mw.app.view.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.mw.app.R;

public class EvenActivity extends AppCompatActivity implements View.OnClickListener{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_layout);
        Button event_layout_btn1 = findViewById(R.id.event_layout_btn1);
        Button event_layout_btn2 = findViewById(R.id.event_layout_btn2);
        Button event_layout_btn3 = findViewById(R.id.event_layout_btn3);
        Button event_layout_btn4 = findViewById(R.id.event_layout_btn4);

        event_layout_btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"匿名类",Toast.LENGTH_LONG).show();
            }
        });

        event_layout_btn3.setOnClickListener(this);
        event_layout_btn4.setOnClickListener(new EventServiceImpl());
    }

    public void eventOnclick(View view){
        Toast.makeText(getApplicationContext(),"onclick属性事件",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(),"继承接口",Toast.LENGTH_LONG).show();
    }

    public class EventServiceImpl implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(),"实现类",Toast.LENGTH_LONG).show();
        }
    }
}

event_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/event_layout_btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="匿名类"></Button>

    <Button
        android:id="@+id/event_layout_btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:onClick="eventOnclick"
        android:text="onclick属性"></Button>

    <Button
        android:id="@+id/event_layout_btn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="继承接口"></Button>

    <Button
        android:id="@+id/event_layout_btn4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="实现类"></Button>
</LinearLayout>

猜你喜欢

转载自blog.csdn.net/m0_37622302/article/details/107742798
今日推荐