When I change the locale of the app, every TextView changes the language but navigation drawer items don't change the language.
I have used
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
drawerView.invalidate();
supportInvalidateOptionsMenu();
}
After locale change, still the language change is not getting reflected in navigation drawer.
But when I restart the activity, the language change is getting reflected in Navigation Drawer.
How to change the language in Navigation Drawer items as soon as the locale is changed ?
You need to reload resources for your app in order to change language. Resources loaded before language change for all text based resources were of previous locale. Now, you need are resources with different locale, after language is changed.
So, the way to do is refresh your whole activity, because, not only different resources are needed, but also, text in different language might have different length and span. So, whole new re-rendering is needed, (otherwise, text will spill over other ui elements, without adjustment).
I will post here the complete code which refreshes the activity on language changed, and everything changes to different locale including navigation drawer items.
Code
src/java/com/pabhinav/testapp/MainActivity.java
package com.pabhinav.testapp;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.Locale;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// THIS PART CHANGES LANGUAGE :
public void changeLanguageClicked(View view) {
String locale = (getResources().getConfiguration().locale.toString().toLowerCase().equals(Locale.US.toString().toLowerCase())) ? "hi" : Locale.US.toString();
Locale myLocale = new Locale(locale);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, MainActivity.class);
startActivity(refresh);
finish();
}
}
src/res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
src/res/layout/app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.pabhinav.testapp.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
src/res/layout/content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.pabhinav.testapp.MainActivity"
tools:showIn="#layout/app_bar_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "#string/change_language"
android:onClick = "changeLanguageClicked"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
src/res/layout/nav_main_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
app:srcCompat="#android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="#string/android_studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
</LinearLayout>
src/res/menu/activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_camera"
android:icon="#drawable/ic_menu_camera"
android:title="#string/import_nav" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/gallery" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/slideshow" />
<item
android:id="#+id/nav_manage"
android:icon="#drawable/ic_menu_manage"
android:title="#string/tools" />
</group>
<item android:title="#string/communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/share" />
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_menu_send"
android:title="#string/send" />
</menu>
</item>
</menu>
src/res/menu/main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
src/res/values/strings.xml
<resources>
<string name="app_name">TestApp</string>
<string name="navigation_drawer_open">Open navigation drawer</string>
<string name="navigation_drawer_close">Close navigation drawer</string>
<string name="action_settings">Settings</string>
<string name="import_nav">Import</string>
<string name="gallery">Gallery</string>
<string name="slideshow">Slideshow</string>
<string name="tools">Tools</string>
<string name="communicate">Communicate</string>
<string name="share">Share</string>
<string name="send">Send</string>
<string name="android_studio">Android Studio</string>
<string name="hello_world">Hello World!</string>
<string name="change_language">Change Language</string>
</resources>
src/res/values-hi/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">परीक्षण ऐप</string>
<string name="navigation_drawer_open">खुले नेविगेशन दराज</string>
<string name="navigation_drawer_close">बंद नेविगेशन दराज</string>
<string name="action_settings">सेटिंग्स</string>
<string name="import_nav">आयात</string>
<string name="gallery">गेलरी</string>
<string name="slideshow">स्लाइड शो</string>
<string name="tools">उपकरण</string>
<string name="communicate">संवाद</string>
<string name="share">शेयर</string>
<string name="send">भेजना</string>
<string name="android_studio">एंड्रॉयड स्टूडियो</string>
<string name="hello_world">नमस्ते दुनिया</string>
<string name = "change_language">भाषा बदलो</string>
</resources>
src/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pabhinav.testapp">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="locale"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Everthing above I have tested and it works fine.
Hope it helps !
Simply put this code before the setContentView in the activity
Locale locale;
locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
activity.getBaseContext().getResources().updateConfiguration(config,
activity.getBaseContext().getResources().getDisplayMetrics());
those who are looking for latest solution in kotlin:
upgrade your appcompat version to 1.6.0 or later
implementation 'androidx.appcompat:appcompat:1.6.0'
create a function
fun setLocale(language: String?) {
val appLocale: LocaleListCompat = LocaleListCompat.forLanguageTags(language)
AppCompatDelegate.setApplicationLocales(appLocale)
}
then use it like
setLocale("en-EN")
it will update and refresh all language change/locale including NavigationView
Related
My navigation drawer doesn't show any items. I changed the background to white, theme has changed but still no items showing up. I am also using the frame layout inside drawer and linear layouts. No errors or messages. What am I doing wrong?
EDIT: I oversimplified my work, but still nothing. No items..
EDIT2: After deleting more I made some progress, now I see that, in preview, my drawer_menu shows up like options menu on top right corner even though in the postLoginactivity.xml file preview shows what I aimed to do. Still no items on emulator.
EDIT3: I have Cutt my code in halve, still can't see what did I do wrong.
activity_post_login.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<!-- burdan sonra komple sıkıntı gibi?-->
<LinearLayout
android:id="#+id/llayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Light" >
<TextView
android:id="#+id/textView"
android:layout_width="326dp"
android:layout_height="45dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:accessibilityLiveRegion="assertive"
android:paddingStart="100dp"
android:paddingEnd="100dp"
android:text="#string/deneme"
android:textSize="30sp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.v7.widget.Toolbar>
<!-- android:layout_height=?attr/actionBarSize-->
<FrameLayout
android:id="#+id/mainFrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toBottomOf="parent"
tools:layout_editor_absoluteX="0dp"/>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
>
<ExpandableListView
android:id="#+id/list_sliderMenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:paddingTop="176dp"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="1dp"
/>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
nav_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="176dp"
android:background="#color/colorPrimary"
android:gravity="bottom"
android:padding="16dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher_round"/>
</LinearLayout>
drawer_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
>
<!--tools:showIn="navigation_view"-->
<group android:checkableBehavior="single"
android:id="#+id/menu_list">
<item android:title="#string/satisYonetimi"
android:id="#+id/satis_yonetimi"/>
<item
android:id="#+id/insanKaynaklari"
android:title="#string/insanKaynaklari" />
<item
android:id="#+id/muhasebeYonetimi"
android:title="#string/muhasebeYonetimi" />
<item
android:id="#+id/aktiviteYonetimi"
android:title="#string/aktiviteYonetimi" />
<item
android:id="#+id/destekYonetimi"
android:title="#string/destekYonetimi" />
</group>
</menu>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="#style/AppTheme" >
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
</resources>
v21\styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="#style/AppTheme" >
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
</resources>
Plus if anyone thinks problem might be somewhere else here are category.java(expandable list), subcategory.java (future sub menus will be implemented ) and and my activity for the drawer to be displayed(under implementation)
category.java
public class Category {
private String cat_name;
private int cat_code;
public void setCat_name(String cat_name) {
this.cat_name = cat_name;
}
public String getCatName(){
return cat_name;
}
public void setCat_code(int cat_code) {
this.cat_code = cat_code;
}
public int getCat_code() {
return cat_code;
}
}
subcategory.java
public class SubCategory {
private String subcat_name;
private String subcat_code;
public void setSubCatName(String subcat_name) {
this.subcat_name = subcat_name;
}
public String getSubCatName(){
return subcat_name;
}
public void setSubCatCode(String subcat_code) {
this.subcat_code = subcat_code;
}
public String getSubCatCode() {
return subcat_code;
}
}
postLogingActicity.java
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import java.util.ArrayList;
public class PostLoginActivity extends AppCompatActivity {
ActionBar bar;
ViewPager viewPager;
FragmentPagerAdapter fpAdapter;
Fragment mMainScreen;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ExpandableListView mCategoryList;
private ArrayList<Category> category_name = new ArrayList<Category>();
private ArrayList <ArrayList<Category>> subcategory_name = new ArrayList
<ArrayList<Category>>();
private ArrayList<Integer> subCatCount = new ArrayList<Integer>();
int previousGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_login);
//Toolbar toolbar =findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
//mDrawerLayout = findViewById(R.id.drawer_layout);
//ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
//mDrawerLayout, toolbar,
// R.string.navigation_drawer_open,
//R.string.navigation_drawer_close);
//mDrawerLayout.addDrawerListener(toggle);
//toggle.syncState();
//this.getCatData();
//Utils.deleteStringFromSp(this, "email");
}
public void onBackPressed(){
if(mDrawerLayout.isDrawerOpen(GravityCompat.START))
mDrawerLayout.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
}
your main activity must be as follows
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="rtl"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
And activity_main_drawer
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_menu7"
android:icon="#drawable/ic_school_black_24dp"
android:title="XXXX" />
<item
android:id="#+id/nav_menu11"
android:icon="#drawable/ic_thumb_up_black_24dp"
android:title="XXXX" />
<item
android:id="#+id/nav_menu12"
android:icon="#drawable/ic_insert_drive_file_black_24dp"
android:title="XXXX" />
<item
android:id="#+id/nav_menu6"
android:icon="#drawable/ic_developer_mode_black_24dp"
android:title="XXXX" />
</group>
</menu>
In Kotlin Navigation Menu
// Navigate Menu
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.nav_menu7 -> {
val intent = Intent(this, Computer::class.java)
startActivity(intent)
}
R.id.nav_menu6 -> {
val menu6 = Menu6()
val fragmentManager = supportFragmentManager
fragmentManager.beginTransaction().replace(R.id.fragment, menu6).addToBackStack(null).commit()
}
R.id.nav_menu12 -> {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://XXXXX"))
startActivity(intent)
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
I hope this solve your problem
Menu works with Activity,Fragment,URL
You've missed to reference the menu of the navigation view
As you named it "drawer_menu_xml", then the modification would be:
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu"/>
NoSuchFieldError in Android Studio.
This problem is occurred while running other application also. I try with other applications also.
Please help me,I can't figure out how this error is coming. Here I want to make a toolbar which have some menu items.
Error:-
java.lang.NoSuchFieldError: No static field title of type I in class
Landroid/support/v7/appcompat/R$id; or its superclasses (declaration of
'android.support.v7.appcompat.R$id' appears in
/data/app/com.example.manojbudhaayer.newapplicaton-2/split_lib_slice_2_apk.apk)
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id ==R.id.profile){
return true;
}
if (id == R.id.setting){
return true;
}
if (id == R.id.mylink){
return true;
}
if (id == R.id.refresh){
return true;
}
return true;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.manojbudhaayer.newapplicaton.MainActivity">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
></android.support.v7.widget.Toolbar>
</LinearLayout>
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/profile"
android:title="Profile"
android:orderInCategory="101"
app:showAsAction="ifRoom"/>
<item android:id="#+id/setting"
android:title="Setting"
android:orderInCategory="102"
app:showAsAction="ifRoom"/>
<item android:id="#+id/mylink"
android:title="My fb Link"
android:orderInCategory="103"
app:showAsAction="ifRoom"/>
<item android:id="#+id/refresh"
android:title="Refresh"
android:orderInCategory="104"
app:showAsAction="ifRoom"/>
</menu>
style.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
</resources>
it's because of both library and module with the same name or inflating multiple XML layouts with duplicate resource id. rename the layout in one of the modules.
I have built an application with an navigation drawer activity in it but now I want it to be present on my other activities as well. I don't want to handle events again and again in different classes.
Also I got suggestions like making one base class and extend that but as I cannot extend more than one class.
Also I also want to use fragments so that I did not have to write the same code again and again
My activity_main.xml is like:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start"
android:background="#color/colorPrimary">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
nav_header.xml is like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="72dp"
android:layout_height="72dp"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#drawable/bcet_logo" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="#string/college_name"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/college_name_full" />
</LinearLayout>
MainActivity.java:
package com.bcetapp.bcetbeta;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_student_list) {
// Handle the camera action
} else if (id == R.id.nav_staff_list) {
} else if (id == R.id.nav_help) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_action_share) {
} else if (id == R.id.nav_contact_us) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/****************************************************************************************USER DEFINED FUNCTIONS******************************************************************/
public void viewMyProfile(View view){
/*intent = new Intent(this, ProfileActivity.class);
startActivity(intent);*/
}
}
activity_main_drawer.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_student_list"
android:icon="#drawable/ic_group"
android:title="Students" />
<item
android:id="#+id/nav_staff_list"
android:icon="#drawable/ic_action_glasses"
android:title=" College Staff" />
<item
android:id="#+id/nav_help"
android:icon="#drawable/ic_action_help"
android:title="help" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_menu_manage"
android:title="Settings" />
</group>
<item android:title="More">
<menu>
<item
android:title="About us"
android:id="#+id/nav_about_us"
android:icon="#drawable/ic_action_info"
/>
<item
android:id="#+id/nav_action_share"
android:icon="#drawable/ic_action_share"
android:title="Share App" />
<item
android:id="#+id/nav_contact_us"
android:icon="#drawable/ic_menu_send"
android:title="contact us" />
</menu>
</item>
</menu>
It's not as easy. There are 2 tech-ticks to achieve it. One is to create use fragment second one is to add the whole code in all activities.
To achieve your result in above case, Add the fragment in your activity and replace/add activities as your required
Also i got suggestions like making one base class and extend that but as I cannot extend more than one class.
True, but the thing about class extension is that you can create a base class that extends AppCompatActivity, and then make your activities extend that base class:
public class BaseClass extends AppCompatActivity...
public class MainActivity extends BaseClass...
This will implicitly cause your MainActivity to extend AppCompatActivity.
How can I create a button inside Android's Toolbar that looks like this iOS example?
ToolBar with Button Tutorial
1 - Add library compatibility inside build.gradle
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
}
2 - Create a file name color.xml to define the Toolbar colors
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ColorPrimary">#FF5722</color>
<color name="ColorPrimaryDark">#E64A19</color>
</resources>
3 - Modify your style.xml file
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/ColorPrimary</item>
<item name="colorPrimaryDark">#color/ColorPrimaryDark</item>
<!-- Customize your theme here. -->
</style>
</resources>
4 - Create a xml file like tool_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:elevation="4dp" />
5 - Include the Toolbar into your main_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar" />
<TextView
android:layout_below="#+id/tool_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/TextDimTop"
android:text="#string/hello_world" />
</RelativeLayout>
6 - Then, put it inside your MainActivity class
package com.example.hp1.materialtoolbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
/* When using AppCompat support library
* (you need to extend Main Activity to
* ActionBarActivity)
* ActionBarActivity has deprecated, use AppCompatActivity
*/
public class MainActivity extends ActionBarActivity {
// Declaring the Toolbar Object
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// Attaching the layout to the toolbar object
toolbar = (Toolbar) findViewById(R.id.tool_bar);
// Setting toolbar as the ActionBar with setSupportActionBar() call
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
7 - And finally, add your "Button Items" to the menu_main.xml inside of /res/menu/ directory
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
<item
android:id="#+id/action_search"
android:orderInCategory="200"
android:title="Search"
android:icon="#drawable/ic_search"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/action_user"
android:orderInCategory="300"
android:title="User"
android:icon="#drawable/ic_user"
app:showAsAction="ifRoom" />
</menu>
Toolbar customization can done by following ways
write button and textViews code inside toolbar as shown below
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:layout_width="wrap_content"
android:layout_height="#dimen/btn_height_small"
android:text="Departure"
android:layout_gravity="right"
/>
</android.support.v7.widget.Toolbar>
Other way is to use item menu as shown below
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
Another possibility is to set the app:actionViewClass attribute in your menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/get_item"
android:orderInCategory="1"
android:text="Get"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.AppCompatButton"/>
</menu>
In your code you can access this button after the menu was inflated:
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.sample, menu);
MenuItem getItem = menu.findItem(R.id.get_item);
if (getItem != null) {
AppCompatButton button = (AppCompatButton) getItem.getActionView();
//Set a ClickListener, the text,
//the background color or something like that
}
return super.onCreateOptionsMenu(menu);
}
I have added text in ToolBar :
menu_skip.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="#+id/action_settings"
android:title="#string/text_skip"
app:showAsAction="never" />
</menu>
MainActivity.java
#Override
boolean onCreateOptionsMenu(Menu menu) {
inflater = getMenuInflater();
inflater.inflate(R.menu.menu_otp_skip, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.menu_item_skip:
Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return true;
}
They are called menu items or action buttons in toolbar/actionbar. Here you have Google tutorial how it works and how to add them
https://developer.android.com/training/basics/actionbar/adding-buttons.html
You can actually put anything inside a toolbar. See the below code.
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:background="#color/colorPrimary">
</android.support.v7.widget.Toolbar>
Between the above toolbar tag you can put almost anything. That is the benefit of using a Toolbar.
Source: Android Toolbar Example
You could use actionLayout from the support library.
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/button_item"
android:title=""
app:actionLayout="#layout/button_layout"
app:showAsAction="always"
/>
</menu>
button_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Activity.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.button_item);
Button btn = item.getActionView().findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Toolbar Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
return true;
}
I was able to achieve that by wrapping Button with ConstraintLayout:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp">
<androidx.appcompat.widget.Toolbar
android:id="#+id/top_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/white_color">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="wrap_content">
<TextView
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cancel"
android:layout_marginStart="5dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn_publish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/publish"
android:background="#drawable/button_publish_rounded"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="10dp"
app:layout_constraintLeft_toRightOf="#id/cancel"
tools:layout_editor_absoluteY="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
You may create a drawable resourcebutton_publish_rounded, define the button properties and assign this file to button's android:background property:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#color/green" />
<corners android:radius="100dp" />
</shape>
I'm using menudrawer library in my project (this one: https://github.com/SimonVT/android-menudrawer).
I'm updating my app to be compatible with API21 (Android 5 Lollipop) and Material Design. When you use this library with API21 menudrawer icon looks bad.
I want to achieve transition you can see in the new Play Store (new menudrawer icon transition to arrow).
What's the best way to do that? Is it possible with this library? The only solution I'm thinking at the moment is custom drawable. But maybe I can use native drawable some way?
OK. I spent few hours with new API and I think that the best for me will be rewriting my drawer from lib to native DrawerLayout.
But maybe this will be useful for someone with similar problem. I've created test project with DrawerLayout (Android Studio -> New Project with menudrawer).
And then I saw the same problem. Wrong icon. If you want to see fancy animation and good icon for Android 5.0 make sure you are using:
import android.support.**v7**.app.ActionBarDrawerToggle;
Take note on v7. By default Fragment class has v4 import and then you won't see good icon.
Another thing. After changing to v7 you need to fix ActionBarDrawerToggle function to new constructor. And that's it. You'll see new drawer icon.
First, make sure you update to latest SDK. Create new Project in Android Studio, then add appcompat-v7.21.0.+ and appcompat-v4.21.0.+ libraries in your buid.gradle as gradle dependency.
compile 'com.android.support:appcompat-v7:21.0.2'
compile 'com.android.support:support-v4:21.0.2'
Add primaryColor and primarycolorDark in your color.xml file.
<resources>
<color name="primaryColor">#2196F3</color>
<color name="primaryColorDark">#0D47A1</color>
</resources>
Add drawer open/close string value in your strings.xml file.
<resources>
<string name="app_name">Lollipop Drawer</string>
<string name="action_settings">Settings</string>
<string name="drawer_open">open</string>
<string name="drawer_close">close</string>
</resources>
Your activity_my.xml layout file looks like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:id="#+id/drawerLayout"
android:layout_height="match_parent">
<!-- activity view -->
<RelativeLayout
android:layout_width="match_parent"
android:background="#fff"
android:layout_height="match_parent">
<TextView
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:textColor="#000"
android:text="Activity Content"
android:layout_height="wrap_content" />
</RelativeLayout>
<!-- navigation drawer -->
<RelativeLayout
android:layout_gravity="left|start"
android:layout_width="match_parent"
android:background="#fff"
android:layout_height="match_parent">
<ListView
android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#eee"
android:background="#fff"
android:dividerHeight="1dp" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Your toolbar.xml layout file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.Toolbar>
Your MyActivity.java looks like this:
Here your activity must extends ActionBarActivity and set your toolbar as support actionbar.
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MyActivity extends ActionBarActivity {
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private ListView leftDrawerList;
private ArrayAdapter<String> navigationDrawerAdapter;
private String[] leftSliderData = {"Home", "Android", "Sitemap", "About", "Contact Me"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
nitView();
if (toolbar != null) {
toolbar.setTitle("Navigation Drawer");
setSupportActionBar(toolbar);
}
initDrawer();
}
private void nitView() {
leftDrawerList = (ListView) findViewById(R.id.left_drawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
navigationDrawerAdapter=new ArrayAdapter<String>( MyActivity.this, android.R.layout.simple_list_item_1, leftSliderData);
leftDrawerList.setAdapter(navigationDrawerAdapter);
}
private void initDrawer() {
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Create style.xml file in values-21 folder for android lollipop
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="myAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryDark">#color/primaryColorDark</item>
<item name="android:statusBarColor">#color/primaryColorDark</item>
<item name="drawerArrowStyle">#style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">#android:color/black</item>
</style>
</resources>
Create your style.xml file in values folder for older versions then android lollipop
<resources>
<style name="myAppTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryDark">#color/primaryColorDark</item>
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="drawerArrowStyle">#style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">#android:color/black</item>
</style>
</resources>
Your AndroidManifest.xml is looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nkdroid.com.lollipopdrawer" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/myAppTheme" >
<activity
android:name=".MyActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
For reference only:
you can download complete source code from here : click here
Check out the new lollipop components released in May 2015 by Android team.
Design Support Library
Blog on Design Support Library