从 Android 8.0(API 级别 26)开始,android:attr/actionBarSize
属性已经被弃用。取而代之的是,在 Android 8.0 及更高版本中,您应该使用android:navigationBarSize
属性来控制导航栏的大小。
以下是如何使用兼容性库获取android:navigationBarSize
属性的示例代码:
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
public class CompatibilityUtils {
@RequiresApi(Build.VERSION_CODES.O)
public static void setActionBarSize(ViewGroup viewGroup, int actionBarSize) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
// Do nothing, the code is not needed since SDK 26 (Android 8.0)
} else {
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewGroup.getLayoutParams();
layoutParams.height = actionBarSize;
viewGroup.setLayoutParams(layoutParams);
}
}
public static int getActionBarSize(View view) {
ViewGroup viewGroup = (ViewGroup) view.getParent();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
// Do nothing, the code is not needed since SDK 26 (Android 8.0)
} else {
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewGroup.getLayoutParams();
return layoutParams.height;
}
return 0;
}
}
要使用这个兼容性库,您只需在您的代码中导入CompatibilityUtils
类,然后调用setActionBarSize
和getActionBarSize
方法。
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewGroup viewGroup = findViewById(R.id.view_group);
CompatibilityUtils.setActionBarSize(viewGroup, 250);
// ... other code ...
}
@Override
protected void onDestroy() {
super.onDestroy();
ViewGroup viewGroup = findViewById(R.id.view_group);
CompatibilityUtils.setActionBarSize(viewGroup, 0);
}
}
在上述代码中,setActionBarSize
方法会将viewGroup
的高度设置为250dp。在onDestroy
方法中,我们再将viewGroup
的高度重置为0,以保持actionBarSize
的值与当前布局相匹配。
领取专属 10元无门槛券
手把手带您无忧上云