要实现ActionBar可见性的Observable/LiveData,可以按照以下步骤进行:
public class ActionBarVisibilityLiveData extends LiveData {
private boolean isVisible = true;
@Override
protected void onActive() {
super.onActive();
// 设置初始可见性
setValue(isVisible);
}
public void setActionBarVisible(boolean isVisible) {
this.isVisible = isVisible;
setValue(isVisible);
}
}
public class MainActivity extends AppCompatActivity {
private ActionBarVisibilityLiveData actionBarVisibilityLiveData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBarVisibilityLiveData = new ActionBarVisibilityLiveData();
// 监听ActionBar的可见性变化
getSupportActionBar().addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() {
@Override
public void onMenuVisibilityChanged(boolean isVisible) {
actionBarVisibilityLiveData.setActionBarVisible(isVisible);
}
});
// 观察ActionBar的可见性
actionBarVisibilityLiveData.observe(this, new Observer() {
@Override
public void onChanged(Boolean isVisible) {
if (isVisible) {
// ActionBar可见
getSupportActionBar().show();
} else {
// ActionBar隐藏
getSupportActionBar().hide();
}
}
});
}
}
这样,当ActionBar的可见性发生变化时,ActionBarVisibilityLiveData会通知观察者,并相应地更新ActionBar的可见性。