本文实现导航栏动态显示隐藏功能。代码基于Android 9.0修改,Android 11 上代码结构有所不同,大的流程差不多,也可以参考本文。
1、导航栏创建加载及隐藏:
?frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
...
try {
// boolean showNav = mWindowManagerService.hasNavigationBar();
// 添加自定义控制状态栏的 Settings.system 属性值,控制初始化时是否创建状态栏
boolean showNav = Settings.system.getInt(mContext.getContentResolver(), "nav_bar_mode", 0) == 0;
// 注册属性值变化监听
mContext.getContentResolver().registerContentObserver(
Settings.System.getUriFor("nav_bar_mode"), false, new SettingsObserver(mHandler), UserHandle.USER_ALL);
if (DEBUG) Log.v(TAG, "hasNavigationBar=" + showNav);
if (showNav) {
createNavigationBar();
}
} catch (RemoteException ex) {
// no window manager? good luck with that
}
...
// 自定义 nav_bar_mode 属性值的监听
private final class SettingsObserver extends ContentObserver {
public SettingsObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange, Uri uri) {
int navMode = Settings.Secure.getInt(mContext.getContentResolver(), "nav_bar_mode", 0);
Log.i("TAG", "navMode = " + navMode);
switch (navMode) {
case 0:
createNavigationBar();
break;
case 1:
mContext.getSystemService(WindowManager.class).removeView(mNavigationBarView);
break;
default:
Log.w(TAG, "Unknown mode");
break;
}
}
}
?这里主要了解导航栏的加载是由系统的?WindowManager 加载,通过addView进行加载显示,所以我们也可以通过 removeView 去进行删除隐藏。
2、加载 view 的源码:
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
public static View create(Context context, FragmentListener listener) {
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_NAVIGATION_BAR,
WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
| WindowManager.LayoutParams.FLAG_SLIPPERY,
PixelFormat.TRANSLUCENT);
lp.token = new Binder();
lp.setTitle("NavigationBar");
lp.accessibilityTitle = context.getString(R.string.nav_bar);
lp.windowAnimations = 0;
View navigationBarView = LayoutInflater.from(context).inflate(
R.layout.navigation_bar_window, null);
if (DEBUG) Log.v(TAG, "addNavigationBar: about to add " + navigationBarView);
if (navigationBarView == null) return null;
context.getSystemService(WindowManager.class).addView(navigationBarView, lp);
FragmentHostManager fragmentHost = FragmentHostManager.get(navigationBarView);
NavigationBarFragment fragment = new NavigationBarFragment();
fragmentHost.getFragmentManager().beginTransaction()
.replace(R.id.navigation_bar_frame, fragment, TAG)
.commit();
fragmentHost.addTagListener(TAG, listener);
return navigationBarView;
}
主要就是?context.getSystemService(WindowManager.class).addView(navigationBarView, lp); 这句。
|