【Android】Android的接口Interface的应用

时间:2022-05-14 08:46:22


定义一个interface接口:

/**
* Created by d on 2016/11/30.
*/

public interface ToastListener {
void showToast();
}


新建类来 调用接口:
/**
* Created by d on 2016/11/30.
*/

public class ToastListenerUser {
private ToastListener mToastListener;

public void setToastListener(ToastListener mToastListener) {
this.mToastListener = mToastListener;
}

public void useToastListener(){
mToastListener.showToast();
}
}


在使用时实现接口:showToast()
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private ToastListenerUser toastListenerUser;
private int i = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

toastListenerUser = new ToastListenerUser();
toastListenerUser.setToastListener(new ToastListener() {
@Override
public void showToast() {
Toast.makeText(MainActivity.this, "回调成功:" + i++, Toast.LENGTH_SHORT).show();
}
});

findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toastListenerUser.useToastListener();
}
});
}

}