您的位置:首页 > 移动开发 > Android开发

改变Android状态栏的颜色

2015-10-08 11:20 597 查看
Android 5.0 Lollipop introduced Material Design theme which automatically colors the status bar based on the ColorPrimaryDark value of the theme.this
requires min API 21



<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
<!-- colorPrimary is used for the default action bar background -->
<item name="colorPrimary">@color/my_awesome_color</item>

<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">@color/my_awesome_darker_color</item>

<!-- colorAccent is used as the default value for colorControlActivated
which is used to tint widgets -->
<item name="colorAccent">@color/accent</item>

<!-- You can also set colorControlNormal, colorControlActivated
colorControlHighlight & colorSwitchThumbNormal. -->
</style>


the way to do this without any Library: if the OS version is not supported - under kitkat - so nothing happend.

added to the top this View:

<View
android:id="@+id/statusBarBackground"
android:layout_width="match_parent"
android:layout_height="wrap_content" />


2.add this method:
public void setStatusBarColor(View statusBar,int color){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//status bar height
int actionBarHeight = getActionBarHeight();
int statusBarHeight = getStatusBarHeight();
//action bar height
statusBar.getLayoutParams().height = actionBarHeight + statusBarHeight;
statusBar.setBackgroundColor(color);
}
}


3. add method get action Bar & status bar height:
public int getActionBarHeight() {
int actionBarHeight = 0;
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
return actionBarHeight;
}

public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}


4.then the only thing you need is this line to set status bar color:
setStatusBarColor(findViewById(
R.id.statusBarBackground),getResources().getColor(android.R.color.white));[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: