android透明背景代码 android状态栏透明效果

前言原来做的效果,如下图(顶部有一条明显的橙色状态栏):
改过之后(顶部状态栏是透明的):
我发现网上写的一些文章,不够简洁明了,我整理了一下,复制粘贴一下就可以在项目中运用 。
首先,在你的Activity中添加下面四个方法(或者封装在一个工具类中)
/** * 全透状态栏 */ protected void setStatusBarFullTransparent() { if (Build.VERSION.SDK_INT >= 21) {//21表示5.0 Window window = getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //虚拟键盘也透明 //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } } /** * 半透明状态栏 */ protected void setHalfTransparent() { if (Build.VERSION.SDK_INT >= 21) {//21表示5.0 View decorView = getWindow().getDecorView(); int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; decorView.setSystemUiVisibility(option); getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //虚拟键盘也透明 // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } } /** * 如果需要内容紧贴着StatusBar * 应该在对应的xml布局文件中,设置根布局fitsSystemWindows=true 。*/ private View contentViewGroup; protected void setFitSystemWindow(boolean fitSystemWindow) { if (contentViewGroup == null) { contentViewGroup = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0); } contentViewGroup.setFitsSystemWindows(fitSystemWindow); } /** * 为了兼容4.4的抽屉布局->透明状态栏 */ protected void setDrawerLayoutFitSystemWindow() { if (Build.VERSION.SDK_INT == 19) {//19表示4.4 int statusBarHeight = getStatusHeight(this); if (contentViewGroup == null) { contentViewGroup = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0); } if (contentViewGroup instanceof DrawerLayout) { DrawerLayout drawerLayout = (DrawerLayout) contentViewGroup; drawerLayout.setClipToPadding(true); drawerLayout.setFitsSystemWindows(false); for (int i = 0; i < drawerLayout.getChildCount(); i++) { View child = drawerLayout.getChildAt(i); child.setFitsSystemWindows(false); child.setPadding(0,statusBarHeight, 0, 0); } } } }然后,在Activity的onCreate()方法中调用即可 。示例如下:
Activity:
public class TestActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); setHalfTransparent(); setFitSystemWindow(false); } protected void setHalfTransparent()... protected void setStatusBarFullTransparent()... protected void setFitSystemWindow()... protected void setDrawerLayoutFitSystemWindow()...}布局文件: