定义一个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();
}
}
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();
}
});
}
}