更新时间:2022-01-12
在 Android 上使用 Observer 与 Observable。
示例
1)创建被观察者 MyObservable
import java.util.Observable;
public class MyObservable extends Observable {
public MyObservable() {}
private volatile static MyObservable myObservable;
public static MyObservable getInstance() {
if (myObservable == null) {
synchronized (MyObservable.class) {
if (myObservable == null) {
myObservable = new MyObservable();
}
}
}
return myObservable;
}
public void postMessage(String msg) {
setChanged();
notifyObservers(msg);
}
}
2)观察者 MainActivity
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.util.Observable;
import java.util.Observer;
public class MainActivity extends AppCompatActivity implements Observer {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (this instanceof Observer) {
MyObservable.getInstance().addObserver(this);
}
findViewById(R.id.post_msg_bt).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MyObservable.getInstance().postMessage("ok");
}
});
}
@Override
public void update(Observable observable, Object obj) {
Log.d("AAAAAAAAA", "msg: " + obj);
}
}
3)activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/post_msg_bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发消息"
/>
</LinearLayout>
4)效果
随手整理,好记性不如烂笔头!
|