对于这种类型的任务。您必须在您的活动或片段中设置第一个 FLAG_LAYOUT_NO_LIMITS 标志为,
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
现在,在您的 XML 中,只需在布局顶部设置一个 view,例如,
<?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"
android:orientation="vertical">
<View
android:id="@+id/status_bar_view"
android:background="#000"
android:layout_width="match_parent"
android:layout_height="24dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="22dp">
//main layout here.
</RelativeLayout>
</LinearLayout>
因此,顶视图取代了布局中的状态栏,您可以根据需要设置视图背景。在上面view,我只是用了黑色,你也可以设置一个渐变作为背景。
编辑
但我们也必须动态设置view,因为每个设备上状态栏的高度根据屏幕大小不同。因此,您计算的状态栏高度为,
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
Above 方法返回每个设备的状态栏高度。您可以将其设置为view 的高度。因此,您的视图看起来与状态栏的大小完全相同。