Android实现自定义监听器有两个主要文件“监听器接口(CustomListenerInterface)”,“监听器处理类(CustomListenerHandle)”,实现之后,你会发现监听器的实现很简单。
1、监听器接口
// CustomListenerInterface
public interface CustomListenerInterface {
// Update the data
public void updateData();
}
2、监听器处理类
这个文件主要是控制监听器的事务
// CustomListenerHandle
private CustomListenerInterface customListenerInterface = null;
// Set the listener
public void setCustomListener(CustomListenerInterface customListenerInterface){
this.customListenerInterface = customListenerInterface;
}
// Handle the data
public void handlerData(){
this.customListenerInterface.updateData();
}
3、在Activity中的实现
public class CustomListenerActivity extends AppCompatActivity {
private Button startListen = null;
private Button endListen = null;
private volatile boolean statue = false;
private CustomListenerHandle listenerHandle = new CustomListenerHandle();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_listener);
this.startListen = findViewById(R.id.start_listen);
this.endListen = findViewById(R.id.end_listen);
// 可以使用匿名内部类实现,也可以实现CustomListenerInterface接口,自定义新类
this.listenerHandle.setCustomListener(new CustomListenerInterface() {
@Override
public void updateData() {
Log.d("**CustomListener**","----数据变化----");
}
});
startListen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("**CustomListener**","--------启动监听--------");
statue = true;
// Start the thread
new Thread(new Runnable() {
@Override
public void run() {
int i=0;
while (statue){
i++;
if(i == 1000000){
listenerHandle.handlerData();
i = 0;
}
}
}
}).start();
}
});
endListen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
statue = false;
Log.d("**CustomListener**","--------停止监听--------");
}
});
}
}
4、xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".CustomListenerActivity">
<TextView
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="自定义监听事件,监听数字的变化"/>
<Button
android:id="@+id/start_listen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始监听"/>
<Button
android:id="@+id/end_listen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="停止监听"/>
</LinearLayout>