Java接口的用法

1.先看效果图,我点击了按钮,就会回调数据
在这里插入图片描述
2.主活动MainActivity2类代码内容如下

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.myapplication001.R;

public class MainActivity2 extends AppCompatActivity {
    
    

    Button btn;
    TextView tv;
    private RequestDouble<String> mRequestResult;

    @SuppressLint({
    
    "MissingInflatedId", "WrongViewCast"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        btn=findViewById(R.id.btn);
        tv=findViewById(R.id.tv);

        //这里采用java8的新特性,接口简写
        this.setmRequestResult(string->{
    
    
            tv.setText(string);
        });
        btn.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                if(mRequestResult!=null){
    
    
                    mRequestResult.result("我在回调数据");
                }
            }
        });
    }

    //定义一个接口
    public interface RequestDouble<String> {
    
    
        void result(String string );
    }

    //设置接口监听
    public void setmRequestResult(RequestDouble<String> mRequestResult) {
    
    
        this.mRequestResult = mRequestResult;
    }
}

3.主活动MainActivity2类的activity_main2布局代码内容如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/refreshLa"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开启接口回调" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:gravity="center"
        android:textColor="@color/black"
        android:textSize="24sp" />
</LinearLayout>

猜你喜欢

转载自blog.csdn.net/qq_36570506/article/details/130446525