I would like to extend AppCompatActivity to centralize codes in order to share codes, e.g. DrawerLayout, etc.
However, I encounter NullPointerException. Here is my code:
MasterActivity
public class MasterActivity extends AppCompatActivity {
public static final String TAG = "MasterActivity";
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void setupDrawer() {
// Drawer
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open_drawer, R.string.close_drawer) {
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
}
}
ChildActivity
public class ChildActivity extends MasterActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
setupDrawer();
}
}
activity_child.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".ChildActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- Main Content -->
</LinearLayout>
<LinearLayout android:id="#+id/llv_left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical"
android:background="#888" >
<!-- Drawer Content -->
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
The NPE appears at:
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
the error message is:
Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerShadow(int, int)' on a null object reference
Obviously the variable mDrawerLayout is null, as findViewById() cannot locate it from layout XML. The R.id.drawer_layout is located at R.layout.activity_child. If the ChildActivity extends AppCompatActivity, the NPE does not appear.
How can I resolve it?
How about
protected void setupDrawer(View v) {
mDrawerLayout = (DrawerLayout)v.findViewById(R.id.drawer_layout);
...
and then in ChildActivity
setContentView(R.layout.activity_child);
setupDrawer(findViewById(android.R.id.content));//use root view
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am developing new android app using navigation drawer and extending
baseactivity and following this link
Same Navigation Drawer in different Activities
but I am getting following exception
Process: edgar.yodgorbek.sportnews, PID: 7608
java.lang.RuntimeException: Unable to start activity ComponentInfo{edgar.yodgorbek.sportnews/edgar.yodgorbek.sportnews.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3102)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3237)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1929)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:209)
at android.app.ActivityThread.main(ActivityThread.java:7021)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
at edgar.yodgorbek.sportnews.BaseActivity.onCreate(BaseActivity.java:44)
at edgar.yodgorbek.sportnews.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:7650)
at android.app.Activity.performCreate(Activity.java:7639)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1295)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3077)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3237)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1929)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:209)
at android.app.ActivityThread.main(ActivityThread.java:7021)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)
below my BaseActivity class
public class BaseActivity extends Activity {
public DrawerLayout drawerLayout;
public ListView drawerList;
public String[] layers;
Toolbar toolbar;
private ActionBarDrawerToggle drawerToggle;
private Map map;
protected void onCreate(Bundle savedInstanceState) {
// R.id.drawer_layout should be in every activity with exactly the same id.
super.onCreate(savedInstanceState);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle( this, drawerLayout,toolbar,0, 0) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.app_name);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// layers = getResources().getStringArray(R.array.layers_array);
drawerList = (ListView) findViewById(R.id.left_drawer);
View header = getLayoutInflater().inflate(R.layout.base_activity, null);
drawerList.addHeaderView(header, null, false);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.base_activity, android.R.id.text1,
layers));
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.base_activity, null, false);
drawerList.addFooterView(footerView);
drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
// map.drawerClickEvent(pos);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
below base_activity.xml
android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Put what you want as your normal screen in here, you can also choose for a linear layout or any other layout, whatever you prefer -->
</FrameLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
below my MainActivity
public class MainActivity extends BaseActivity {
public List<Article> articleList = new ArrayList<Article>();
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
private SportNews sportNews;
private ArticleAdapter articleAdapter;
private DrawerLayout drawerLayout;
private ListView drawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
SportInterface sportInterface = SportClient.getApiService();
Call<SportNews> call = sportInterface.getArticles();
call.enqueue(new Callback<SportNews>() {
#Override
public void onResponse(Call<SportNews> call, Response<SportNews> response) {
sportNews = response.body();
if (sportNews != null && sportNews.getArticles() != null) {
articleList.addAll(sportNews.getArticles());
}
articleAdapter = new ArticleAdapter(articleList, sportNews);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(articleAdapter);
}
#Override
public void onFailure(Call<SportNews> call, Throwable t) {
}
});
}
}
below activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
Actually, your BaseActivity has not Layout Set(setContentView) so indeed the DrawerLayout will be null, you should Not declare View/findViewById in your BaseActivity, also, the super.onCreate() in your MainActivity trigger before everything the onCreate() in the BaseActivity and thus causing the crash
Write the below line After super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i created navigation drawer in base activity and extends in main activity but there is no result in main activity
Here is my code:
BaseActivity Java code:
public class BaseActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
ListView mDrawerList;
String[] items;
ActionBarDrawerToggle mDrawerToggle;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
items = getResources().getStringArray(R.array.menu);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, items));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close){
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
});
}
public void selectItem(int position){
Intent intent;
switch (position)
{
case 0:
intent = new Intent(this,OneActivity.class);
startActivity(intent);
break;
case 1:
intent = new Intent(this,TwoActivity.class);
startActivity(intent);
break;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
And here is my Xml Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:toolbar="http://schemas.android.com/apk/res-auto"
android:id="#+id/tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
toolbar:navigationIcon="#drawable/ic_navigation">
</android.support.v7.widget.Toolbar>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/drawer_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/colorAccent"
android:choiceMode="singleChoice"
android:divider="#android:color/holo_blue_dark"
android:dividerHeight="1dp">
</ListView>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
And here is MainActivity:
public class MainActivity extends BaseActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
}
}
suggest me the right answer
create a constructor in baseActivity class and call your defined functions of baseActivity class in constructor and than call that constructor in your MainActivity class function onCreate(Bundle savedInstanceState).
I have several activities where I want to use the same navigation drawer. Here's part of my Activity class code related to the drawer:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
I'm planning to make a DrawerActivity class and extend it from all those activities which want the Navigation drawer. Therefore, I will have to move all the drawer code to that DrawerActivity.
The problem:
toolbar is important for the initialization of ActionBarDrawerToggle. Every activity has a different toolbar depending upon the needs of that activity. Therefore, the toolbar layouts must be kept in their respective layout xml files. How would I use the toolbar then in the DrawerActivity class?
Layout xml for the drawer:
<?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">
<FrameLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/frame_layout"
xmlns:android="http://schemas.android.com/apk/res/android">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
app:itemBackground="#drawable/drawer_list_selector"
style="#style/NavigationDrawer"
app:headerLayout="#layout/sidenav_header"
app:menu="#menu/side_navigation_menu"
app:theme="#style/Drawer"/>
</android.support.v4.widget.DrawerLayout>
Here's the SideNavigation activity (which I'm trying to extend by those classes who need navigation drawer): pastebin.com/hheMXku5
main statement of the log says:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
Here's the link to the onCreate of one of the activity class that extends the SideNavigation class: pastebin.com/iKYXVbda
okey so as you want to use drawer with Activity. I am posting my code here. I hope this will help you out.
First of all you need to develop NavigationDrawer. I know you can do it by your self.
Now create child Activity for Example Home.java and extend it with your drawer Activity let's say MainActivity.java.
it will be something like this.
public class Home extends MainActivity{
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Now usually we perform setContentView in onCreate, bur here do something like this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.home, frameLayout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
Where frameLayout would be your container, which you have take in MainActivity.
Note : don't forget to take another ToolBar in home Activity. because it will override MainActivity's toolbar.
EDIT
I am posting my Whole code please refer it. Although I have took my custom Navigation drawer but it can work with NavigationView too.
activity_main
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >
<RelativeLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="false" >
<!-- ToolBar of MainActivity -->
<include
android:id="#+id/toolbar_headers"
layout="#layout/toolbar_header" />
</RelativeLayout>
<!-- here will be your NavigationView -->
<com.random.extraclasses.ScrimInsetsFrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_marginRight="-8dp"
android:elevation="8dp"
android:fitsSystemWindows="true"
app:insetForeground="#4000" >
<include
android:id="#+id/drawar_layout"
layout="#layout/drawar_layout" />
</com.gujarat.property.extraclasses.ScrimInsetsFrameLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements OnClickListener {
protected RelativeLayout frameLayout;
protected DrawerLayout mDrawerLayout;
protected ListView mDrawerList;
protected ScrimInsetsFrameLayout mLayout;
protected ActionBarDrawerToggle mDrawerToggle;
protected static boolean isLaunch = true;
Toolbar toolbar;
private CharSequence mTitle;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
frameLayout = (RelativeLayout) findViewById(R.id.frame_container);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list);
mLayout = (ScrimInsetsFrameLayout) findViewById(R.id.container);
toolbar = (Toolbar) findViewById(R.id.toolbar_headers);
setSupportActionBar(toolbar);
navDrawerItems = new ArrayList<NavDrawerItem>();
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1)));
navMenuIcons.recycle();
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectedPos = position - 1;
displayView(position);
}
});
mDrawerList.setAdapter(adapter);
mDrawerList.setFocusable(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name) {
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (isLaunch) {
isLaunch = false;
displayView(0);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displayView(int position) {
mDrawerLayout.closeDrawer(mLayout);
MainActivity.position = position;
switch (position) {
case 0:
if (this.getClass().getSimpleName().equals("Home")) {
} else {
Intent i = new Intent(this, Home.class);
startActivity(i);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
break;
case 1:
if (this.getClass().getSimpleName().equals("ForSale")) {
} else {
Intent i = new Intent(this, ForSale.class);
startActivity(i);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
break;
case 2:
if (this.getClass().getSimpleName().equals("ForRent")) {
} else {
Intent i = new Intent(this, ForRent.class);
startActivity(i);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
break;
case 3:
if (this.getClass().getSimpleName().equals("NewProjects")) {
} else {
Intent i = new Intent(this, NewProjects.class);
startActivity(i);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
break;
default:
break;
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onClick(View v) {
}
}
And finally Home.java
public class Home extends MainActivity implements OnClickListener {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.home, frameLayout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("");
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (mDrawerLayout.isDrawerOpen(mLayout)) {
isLaunch = false;
mDrawerLayout.closeDrawer(mLayout);
} else {
finishAffinity();
}
}
And just for reference home.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar"
android:background="#drawable/back51" >
<TextView
android:id="#+id/etSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#android:color/transparent"
android:text="Search Property"
android:textColor="#666666" />
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlways"
android:background="#color/toobar"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
</android.support.v7.widget.Toolbar>
</RelativeLayout>
I hope this will help you out.
I have an activity with navigation drawer and toolbar
Activity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private CustomTextViewMondaRegular tvTitle;
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
tvTitle = (CustomTextViewMondaRegular) findViewById(R.id.actionTitle);
tvTitle.setText(getIntent().getStringExtra("title"));
mDrawerList.setAdapter(new NavAdapter(getApplicationContext()));
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,toolbar,
R.string.title_activity_main, R.string.title_activity_main) {
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
// creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Logger.e("pos", position + "");
}
}
}
Activity XML
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.vf.MainActivity">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/tool_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#android:color/white"
android:elevation="3dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/MyDarkToolbarStyle">
<TextView
android:id="#+id/actionTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:drawableEnd="#drawable/logo"
android:drawableRight="#drawable/logo"
android:gravity="center"
android:text="XXXXXX"
android:textColor="#000000"
android:textSize="18sp" />
</android.support.v7.widget.Toolbar>
</FrameLayout>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
android:choiceMode="singleChoice"
android:divider="#D8D8D8" />
The toggle icon currently shows the default icon. I need to change that icon. How can I do that?
For people who come across this SO question in future,
We have to disable drawer indicator
mDrawerToggle.setDrawerIndicatorEnabled(false);
and then set ToolBar's navigation button
mToolbar.setNavigationIcon(R.drawable.navIcon);
P.S. after that we have to set Navigation click listner on toolbar and open NavigationDrawer manualy.
like
mToolbar.setNavigationOnClickListener :D
Try the code below:
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_drawer);
mDrawerToggle.setDrawerIndicatorEnabled(false);
and open the drawer with
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.openDrawer(Gravity.START);
}
});
You can set the menu icon using setHomeAsUpIndicator, pass a drawable to this method.
See code below:
ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
I am using a lollipop (api level 21).I had implemented the navigation
drawer in my application.Everything was exactly fine.But I didn't see
the navigation drawer at the end of output.
I didn't get any error at runtime.My only problem is,I didn't know
why I didn't get the navigation drawer at the end.
Below I am posted the codes relevant to that.
ChapterActivity.java:
public class ChapterActivity extends ActionBarActivity implements OnItemClickListener {
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer,
R.string.app_name,
R.string.app_name
) {
public void onDrawerClosed(View view) {
setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
initialize();
listChapter.setOnItemClickListener(this);
mDrawerList.setOnItemClickListener(this);
}
private void initialize() {
......
actionBar();
}
public void actionBar() {
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color
.parseColor("#FFFFFF")));
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
}
public class getChapter extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
chapterList = DatabaseQueryHelper.getInstance().getChapters();
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
ac = new AdapterChapter(ChapterActivity.this, chapterList); // AdapterChapter
listChapter.setAdapter(ac);
mDrawerList.setAdapter(ac);
}
}
}
activity_chapter.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textviewHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:fontFamily="fonts/Dosis.otf"
android:text="#string/heading_chapter"
android:textSize="25sp"
android:visibility="gone" />
<ListView
android:id="#+id/listviewChapters"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/imageviewBanner"
android:layout_below="#+id/textviewHeading"
android:layout_marginTop="5dp" >
</ListView>
<ImageView
android:id="#+id/imageviewBanner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:src="#drawable/banner"
android:visibility="invisible" />
</RelativeLayout>
</FrameLayout>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/list_background"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</android.support.v4.widget.DrawerLayout>
styles.xml:
<resources>
<style name="AppBaseTheme" parent="#style/Theme.AppCompat"></style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
</resources>
Finally I didn't seen the navigation drawer in home page.Anyone can help me with this.Where I did wrong.Thank you.
It seems you are using android.support.v4.app.ActionBarDrawerToggle . This class is deprecated and you should use android.support.v7.app.ActionBarDrawerToggle, which also has a different constructor.
public ActionBarDrawerToggle (Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes)
public ActionBarDrawerToggle (Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes)
The first links with you actual action bar. You just need to remove the reference to ic_launcher, and switch v4.app.ActionBarDrawerToggle to v7.app.ActionBarDrawerToggle in your imports.
The second ties with a Toolbar view, which I think you did not implement.
Second issue I see is a missing call when overriding onDrawerOpened() and onDrawerClosed() method. You should always call the super class:
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
// other stuff
}
same goes for onDrawerOpened().