CustomListenerInterface.java
public interface CustomListenerInterface {
// Update the data
public void updateData();
}
MainActivity.java
public class MainActivity 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_main);
init();
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**","--------停止监听--------");
}
});
}
private void init() {
this.startListen = findViewById(R.id.start_listen);
this.endListen = findViewById(R.id.end_listen);
}
public class CustomListenerHandle {
private CustomListenerInterface customListenerInterface = null;
//设置监听器
public void setCustomListener(CustomListenerInterface customListenerInterface){
this.customListenerInterface = customListenerInterface;
}
//处理程序数据
public void handlerData(){
this.customListenerInterface.updateData();
}
}
}
activity_main.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=".MainActivity">
<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>
源码:
链接:https://pan.baidu.com/s/1sLrJrC3mH6_OWt46TpX6wQ
提取码:gzl5