Android interface接口的使用笔记
Android的interface类似iOS的的协议委托Protocol,所以说尽管编程语言不通,但是思路是一致的!
1、传this实例给被委托类的interface对象
创建被委托类实例,传this过去
bottomNavigatorView = (BottomNavigatorView) findViewById(R.id.bottomNavigatorView);
if (bottomNavigatorView != null) {
bottomNavigatorView.setOnBottomNavigatorViewItemClickListener(this);
}
被委托类:
public void setOnBottomNavigatorViewItemClickListener(OnBottomNavigatorViewItemClickListener listener) {
this.mOnBottomNavigatorViewItemClickListener = listener;
}
OnBottomNavigatorViewItemClickListenermOnBottomNavigatorViewItemClickListener;
public interface OnBottomNavigatorViewItemClickListener {
void onBottomNavigatorViewItemClick(int position, View view);
}
委托类实现方法
@Override //实现了接口方法
public void onBottomNavigatorViewItemClick(int position, View view) {
System.out.println("我响应了接口方法");
setCurrentTab(position);
}
注意这种需要在委托类中实现接口implements BottomNavigatorView.OnBottomNavigatorViewItemClickListener
2、不传this实例给interface,而是直接在本类set方法中创建接口实例,然后响应接口的回调(实现接口的方法)
委托类代码:
@Override
public void onViewCreated(View view,@Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
tabLayout.setOnTabItemClickListener(new TabLayout.OnTabItemClickListener() {
@Override
public void onTabItemClick(int position, View view) {
System.out.println("点击当前tab");
setCurrentTab(position);
}
});
}
被委托类代码:
private OnTabItemClickListenermOnTabItemClickListener;//定义一个监听tat点击事件的接口
public interface OnTabItemClickListener {
void onTabItemClick(int position, View view);
}
//注意实现它的set方法
public void setOnTabItemClickListener(OnTabItemClickListener listener) {
this.mOnTabItemClickListener = listener;
}
触发入口
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mOnTabItemClickListener.onTabItemClick(finalI, v);
}
});
这种方式不需要实现接口
大家觉得常用哪种方式呢?