Gradient status bar are a new trend in mobile apps to make UI beautiful (Like iOS). here we are going to create toolbar with gradient background that will match with status color. Toolbar and status bar are separate entities in Android.Thus there is no straightforward way to have a single gradient from the top of the screen to the bottom edge of our toolbar. But there are hacks to achieve this. Let’s see how we can do it. It will work lollipop and above.
Step 1:
First we need to create drawable xml file for gradient background. gradient_theme.xml
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:angle="0"
android:startColor="#fa9f46"
android:endColor="#F6416C"/> </shape>
2. Use a style that doesn’t contain any ActionBar, like this one.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
3. Or alternatively, override the style
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style>
And in your activity’s onCreate method, add the following:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStatusBarGradiant(this); setContentView(R.layout.activity_main); } protected void setStatusBarGradiant(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = activity.getWindow(); Drawable background = activity.getResources().getDrawable(R.drawable.gradient_theme); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(activity.getResources().getColor(android.R.color.transparent)); window.setBackgroundDrawable(background); } } }
And in your activity_main.xml file, add the following:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="@android:color/white"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:title="Gradiant"
app:titleTextColor="@android:color/white"
android:background="@drawable/gradient_theme"> </android.support.v7.widget.Toolbar> </android.support.constraint.ConstraintLayout>
Happy Coding...
EmoticonEmoticon