In Android, graphics are often handled by a resource called a Drawable. In the following step you learn how to create a certain type of Drawable called a ShapeDrawable, and apply it to your ImageButton elements as a background.
A ShapeDrawable is a primitive geometric shape defined in an XML file by a number of attributes including color, shape, padding and more. It defines a vector graphic, which can scale up and down without losing any definition.
- Choose New > Drawable resource file.
- Change xml code of the new resource to :
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="2dp"
android:color="@color/colorPrimary"/>
</shape>- The Android platform supplies a large collection of styles and themes.
- Using styles can reduce the amount of code needed for your UI components.
- A style can specify common properties such as height, padding, font color, font size, and background color.
- A style should not include layout-related information.
- A style can be applied to a View, Activity, or the entire app. A style applied to an Activity or the entire app must be defined in the AndroidManifest.xml file.
- To inherit a style, a new style identifies a parent attribute in the XML.
- When you apply a style to a collection of View elements in an activity or in your entire app, that is known as a theme.
- To apply a theme, you use the android:theme attribute.
- To apply a theme to an activity instead of the entire application, place the theme attribute in the tag instead of the tag. For more information on themes and styles, see the Style and Theme Guide.
- The Android framework provides a theme that is designed exactly for this: The DayNight theme.
- The DayNight theme uses the AppCompatDelegate class to set the night mode options in your Activity. To learn more about this theme, visit this blog post.
- In your styles.xml file, modify the parent of AppTheme to "Theme.AppCompat.DayNight.DarkActionBar".
- in the code to change the theme:
if(item.getItemId()==R.id.night_mode){
// Get the night mode state of the app.
int nightMode = AppCompatDelegate.getDefaultNightMode();
//Set the theme mode for the restarted activity
if (nightMode == AppCompatDelegate.MODE_NIGHT_YES) {
AppCompatDelegate.setDefaultNightMode
(AppCompatDelegate.MODE_NIGHT_NO);
} else {
AppCompatDelegate.setDefaultNightMode
(AppCompatDelegate.MODE_NIGHT_YES);
}
// Recreate the activity for the theme change to take effect.
recreate();- don't forget about the savedinstancestate because we are recreating the activity.