I'm trying to make a Navigation Drawer, I'm reading a lot of guides on how to do this and I think it should work now, but the Drawer does not open when I click on the title (when I manually try to open it, then the icon will get smaller, but still no menu appears). Also, I'm not getting any errors or exception, so I think I might be missing something which I cannot figure out myself.
This is the code of my BaseActivity (the drawer activity which gets extended by my MainActivity):
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class BaseActivity extends Activity {
public DrawerLayout drawerLayout;
public ListView drawerList;
private String[] drawerListEntries;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
drawerListEntries = getResources().getStringArray(R.array.drawer_items);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_navigation_drawer, R.string.drawer_open, R.string.drawer_close)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(R.string.hello_world);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
drawerList = (ListView) findViewById(R.id.drawer_list);
drawerList.setAdapter(new ArrayAdapter<String>(getBaseContext(), R.layout.drawer_list_item, drawerListEntries));
drawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int pos, long arg3) {
String selectedValue = (String) drawerList.getAdapter().getItem(pos);
Toast.makeText(getBaseContext(), selectedValue, Toast.LENGTH_SHORT).show();
}
});
}
#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);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = drawerLayout.isDrawerOpen(drawerList);
menu.findItem(R.id.action_user).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
}
This is my activity_base.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">
<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="wrap_content"
android:background="#color/light_blue"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:choiceMode="singleChoice"
android:layout_gravity="start"
/>
</android.support.v4.widget.DrawerLayout>
This is my drawer_list_item.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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/drawer_list_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="12dp"
android:textSize="24sp"
android:textColor="#color/belize_hole"
android:fontFamily="sans-serif-light">
</TextView>
</LinearLayout>
And this is my MainActivity.java which extends BaseActivity:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class HomeActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
//return super.onCreateOptionsMenu(menu);
return true;
}
}
Anyone who can see the problem?
You are overriding content view from BaseActivity by calling setContentView(R.layout.activity_home); in HomeActivity.
I suggest you to switch fragments instead of activities with Navigation Drawer, it's the best way. So you will have one hosting activity with Navigation Drawer and you'll switch only views inside FrameLayout, for instance. Take a look here http://developer.android.com/training/implementing-navigation/nav-drawer.html
Related
I am trying to set a tab layout inside a fragment and call it by an option inside navigation drawer but I am getting a null object reference error.
I am setting my navigation drawer inside Main2Activity
Main2Activity
import android.content.Intent;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.example.fireapp.model.Users;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.example.fireapp.ui.main.SectionsPagerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private View headerView;
private TextView usernameText;
private TextView emailText;
private CircleImageView userImage;
private FirebaseUser firebaseUser;
private DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("fireApp");
//navigation drawer
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
//user details
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
headerView = navigationView.getHeaderView(0);
usernameText = headerView.findViewById(R.id.usernameText);
userImage = headerView.findViewById(R.id.userImage);
emailText = headerView.findViewById(R.id.userEmail);
setUserDetails();
// if(savedInstanceState==null) {
// getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
// new chatFragment()).commit();
// navigationView.setCheckedItem(R.id.nav_chat);
// }
}
private void setUserDetails() {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
usernameText.setText(user.getUsername());
emailText.setText(firebaseUser.getEmail());
if (user.getImageUrl().equals("default")) {
userImage.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(getApplicationContext()).load(user.getImageUrl()).into(userImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.nav_chat:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new chatFragment()).commit();
break;
case R.id.nav_share:
Toast.makeText(this, "Share!", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_feedback:
Toast.makeText(this, "Feedback!", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//3 dots menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.logout) {
AuthUI.getInstance()
.signOut(Main2Activity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
finish();
}
});
return true;
} else
return false;
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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:context=".Main2Activity"
tools:openDrawer="end">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer_menu"></com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
chatFragment
package com.example.fireapp;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.fireapp.ui.main.SectionsPagerAdapter;
import com.google.android.material.tabs.TabLayout;
public class chatFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_chat,container,false);
tabLayout=view.findViewById(R.id.tabs);
viewPager=view.findViewById(R.id.view_pager);
viewPager.setAdapter(new SectionsPagerAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
}
fragment_chat.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".chatFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</FrameLayout>
SectionPagerAdapter
package com.example.fireapp.ui.main;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.fireapp.R;
import com.example.fireapp.tab1;
import com.example.fireapp.tab2;
import com.example.fireapp.tab3;
import java.util.List;
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2,R.string.tab_text_3};
private Context mContext ;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
public SectionsPagerAdapter(FragmentManager childFragmentManager) {
super(childFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0 :
tab1 tab1 = new tab1();
return tab1;
case 1:
tab2 tab2 = new tab2();
return tab2;
case 2:
tab3 tab3 = new tab3();
return tab3;
}
return null;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
I am getting the following error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fireapp, PID: 6785
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at com.example.fireapp.ui.main.SectionsPagerAdapter.getPageTitle(SectionsPagerAdapter.java:61)
at com.google.android.material.tabs.TabLayout.populateFromPagerAdapter(TabLayout.java:1323)
at com.google.android.material.tabs.TabLayout.setPagerAdapter(TabLayout.java:1314)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1227)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1188)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1168)
at com.example.fireapp.chatFragment$1.run(chatFragment.java:32)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I am new to android development please help.
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()'
on a null object reference
NullPointerException is thrown when an application attempts to use an object reference that has the null value.
You can try with this
private String TAB_TITLES[] = new String[]{"Tab1", "Tab2", "Tab3"};
Then
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return TAB_TITLES[position];
}
getPageTitle() - This method may be called by the ViewPager to obtain a title string to describe the specified page.
I have created a navigation drawer in my AbstractActivity.class and i want to use that drawer in all my activities , so i created another drawer class and extending that class in another activity but it isnt working , can anyonetell me whats wrong in my code ?
Abstractactivity.class
package com.astro.famouspandit.Activities.Abstract;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Image;
import android.os.Bundle;
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;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.astro.famouspandit.Activities.Activity.ChartStyle;
import com.astro.famouspandit.Activities.Activity.Contact;
import com.astro.famouspandit.Activities.Activity.Settings;
import com.astro.famouspandit.Activities.Activity.Welcome;
import com.astro.famouspandit.R;
public class AbstractActivity extends AppCompatActivity {
private String[] mPlanetTitles;
private LinearLayout mDrawerList;
protected DrawerLayout mDrawerLayout;
protected ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
protected Toolbar toolbar;
protected FrameLayout framelayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_abstract);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (LinearLayout) findViewById(R.id.left_drawer);
framelayout = (FrameLayout)findViewById(R.id.content_frame);
mTitle = mDrawerTitle = getTitle().toString();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
toolbar, R.string.drawer_open, R.string.drawer_close){
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_Aboutus).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void selectItem(int position) {
switch(position) {
case 1:
Intent a = new Intent(this, Welcome.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(this, Welcome.class);
startActivity(b);
break;
default:
}
}
public boolean onOptionsItemSelected(MenuItem item){
int items = item.getItemId();
switch(items){
case R.id.action_Settings:{
Intent intent = new Intent(this,Settings.class);
startActivity(intent);
}break;
case R.id.action_Contact_us:{
Intent intent = new Intent(this,Contact.class);
startActivity(intent);
}break;
case R.id.action_Aboutus:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
case R.id.action_Profile:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
}
return super.onOptionsItemSelected(item);
}
}
activity_abstract.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">
<include layout="#layout/toolbar"/>
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<LinearLayout android:id="#+id/left_drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#0F6177">
<LinearLayout android:id="#+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="#layout/navigation_drawer"></include>
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
NavigationActivity.class
package com.astro.famouspandit.Activities.Abstract;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
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.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.astro.famouspandit.R;
public abstract class NavigationActivity extends AppCompatActivity implements View.OnClickListener{
protected DrawerLayout mDrawerLayout;
private LinearLayout mFrameLayout_HeaderView;
protected FrameLayout mFrameLayout_ContentFrame;
protected ActionBarDrawerToggle mActionBarDrawerToggle;
protected Toolbar mToolbar;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mFrameLayout_ContentFrame = (FrameLayout) findViewById(R.id.main_activity_content_frame);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mFrameLayout_HeaderView = (LinearLayout) findViewById(R.id.mainLayout);
mFrameLayout_HeaderView.setOnClickListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.main_activity_DrawerLayout);
mDrawerLayout.closeDrawers();
mDrawerLayout.setStatusBarBackground(R.color.colorPrimary);
mActionBarDrawerToggle = new ActionBarDrawerToggle
(
this,
mDrawerLayout,
mToolbar,
R.string.drawer_open,
R.string.drawer_close
) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Disables the burger/arrow animation by default
super.onDrawerSlide(drawerView, 0);
}
};
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
mActionBarDrawerToggle.syncState();
}
}
activity_navigationactivity.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_activity_DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- The main content view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/main_activity_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer -->
<include layout="#layout/navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
class where i am extending NavigationActivity Class
public class Welcome extends NavigationActivity implements View.OnClickListener{
private CardView mAstro,mMatch,mPanch,mAsk,mContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_welcome,mFrameLayout_ContentFrame);
This is a fairly common question has been blogged about. Essentially, you want to create a BaseActivity with a layout that contains the Navigation Drawer and then have your other Activities extend the BaseActivity and inflate their layouts within the BaseActivity's layout. This way you have the Navigation Drawer in all your activity and reuse the code for setting up the Drawer (since that code lives in the BaseActivity).
You can find an example implementation along with a more detailed explanation here: http://lucas-dev.com/blog/entry/base-activities-sliding-menu.html
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
i'm trying to create a sliding drawer. I spent forever getting my imports to match my code, in terms of getSupportActionBar vs getActionBar etc., I suspect the issue is somewhere in the activity_main.xml but I'm at a loss for what to put there.
MainActivity.java
package me.paxana.alerta;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.app.Fragment;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import me.paxana.alerta.adapter.SlidingMenuAdapter;
import me.paxana.alerta.fragment.Fragment1;
import me.paxana.alerta.fragment.Fragment2;
import me.paxana.alerta.fragment.Fragment3;
import me.paxana.alerta.model.ItemSlideMenu;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private List<ItemSlideMenu> listSliding;
private SlidingMenuAdapter adapter;
private ListView listViewSliding;
private DrawerLayout drawerLayout;
private android.support.v7.app.ActionBarDrawerToggle actionBarDrawerToggle;
private Toolbar mToolbar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
}
else {
Log.i(TAG, currentUser.getUsername());
}
listViewSliding = (ListView)findViewById(R.id.lv_sliding_menu);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
listSliding = new ArrayList<>();
//add item for sliding list
listSliding. add(new ItemSlideMenu(R.drawable.ic_action_settings, "Settings"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_about, "About"));
listSliding.add(new ItemSlideMenu(R.mipmap.ic_launcher, "Android"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//display icon to open/close slider
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
assert getActionBar() != null;
getActionBar().setDisplayHomeAsUpEnabled(true);
//set title
setTitle(listSliding.get(0).getTitle());
//item selected
listViewSliding.setItemChecked(0, true);
//close menu
drawerLayout.closeDrawer(listViewSliding);
//handle on item click
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//set title
setTitle(listSliding.get(position).getTitle());
//item selected
listViewSliding.setItemChecked(position, true);
//close menu
drawerLayout.closeDrawer(listViewSliding);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int itemId = item.getItemId();
if (itemId == R.id.action_logout) {
ParseUser.logOut();
navigateToLogin();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
//create method replace fragment
private void replaceFragment(int pos) {
android.support.v4.app.Fragment fragment = null;
switch (pos) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
fragment = new Fragment1();
break;
}
if(null != fragment) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar 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"
android:id="#+id/drawer_layout"
tools:context="me.paxana.alerta.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_content">
</RelativeLayout>
<ListView
android:layout_width="200dp"
android:layout_height="match_parent"
android:id="#+id/lv_sliding_menu"
android:background="#FFFFFF"
android:choiceMode="singleChoice"
android:layout_gravity="start" />
</android.support.v7.widget.Toolbar>
Why are you using android.support.v7.widget.Toolbar for your main_layout root tag? That's not what android says.
You should use that Toolbar just for using Toolbar with your activity.
See: setContentView(R.layout.activity_main);
That won't work at all.
Use it like this:
<?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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="me.paxana.alerta.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/ColorPrimary"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<ListView
android:id="#+id/lv_sliding_menu"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF"
android:choiceMode="singleChoice" />
</RelativeLayout>
I'd rather to use CoordinatorLayout with AppCompat or this Toolbar implementation too.
Also,
//display icon to open/close slider
mToolbar = (Toolbar) findViewById(R.id.toolbar);
Here you were using toolbar as that Toolbar id.
Use it like this in your xml:
android:id="#+id/toolbar"
Above code should work now.Also, you've many not used in your imports like:
import android.support.v7.app.ActionBarActivity;
and etc.
Read the docs please.
Use this
R.id.drawer_layout
Instead of
R.id.toolbar
am trying to implement a button to the left in the navigation bar in my android app. I want this button to open the navigation drawer. Right now the only thing I can to is to swipe from left top right to open it.
I have tried to google, and read the documentation. Could someone please help?
My code MainActivity.java is added below. Thanks!
package safefence.tc.safefence;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity implements LocationListener {
ArrayList<NavigationDrawerItem> listItems;
DrawerLayout drawerLayout;
ActionBarDrawerToggle drawerToggle;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = new ArrayList<NavigationDrawerItem>();
listItems.add(new NavigationDrawerItem("Home", R.drawable.ic_drawer));
listItems.add(new NavigationDrawerItem("About", R.drawable.ic_drawer));
listItems.add(new NavigationDrawerItem("Follow", R.drawable.ic_drawer));
listItems.add(new NavigationDrawerItem("Log out", R.drawable.ic_drawer));
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.red_string,R.string.abc_action_mode_done) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View view) {
super.onDrawerOpened(view);
}
};
drawerLayout.setDrawerListener(drawerToggle);
list = (ListView) findViewById(R.id.drawer);
list.setAdapter(new NavDrawerAdapter(this, listItems));
list.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = drawerLayout.isDrawerOpen(list);
return super.onPrepareOptionsMenu(menu);
}
#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);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onProviderDisabled(String provider) { }
}
XML file
<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_height="match_parent"
android:layout_width="match_parent" >
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment">
</fragment>
</FrameLayout>
<ListView
android:id="#+id/drawer"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"
android:layout_width="240dp"
android:layout_height="match_parent">
</ListView>
</android.support.v4.widget.DrawerLayout>
To add icon
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.red_string,R.string.abc_action_mode_done)
ic_drawer will be your icon.
If you working on sliding menu See this link. This is a good tutorial.
I trying find more info how create best Navigation Drawer panel with Material Desing's guidelines.
Google recommended page Creating a Navigation Drawer. This example based on Support Library v4.
Also link about v7 AppCompat v21 — Material Design for Pre-Lollipop Devices!. This work fine only on Android API 21+. I can't use this Material Desing in lower OS's vesion, because If I set target=android-20 (or less) in project.properties I get errors in Eclipse (several hundred):
C:\<workspace>\android-support-v7-appcompat\res\values-v21\styles_base.xml:75: error: Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.ActionButton'
....
:( several hundred error in 'values-v21' directory
....
I use features of low Android API, that was deprecated or undefined in Android API 21+. But I need support Material Design in low API (14+).
Please give examples of creating Navigation Drawer on low Android API 14+.
Use this as a dependency :
compile "com.android.support:appcompat-v7:21.0.2" (or use newer)
Layout :
<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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/toolbar"
android:id="#+id/mytoolbardrawer"
/>
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_below="#id/mytoolbardrawer"
android:layout_height="match_parent"
/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/rel_drawer"
android:layout_width="304dp"
android:layout_height="match_parent"
android:layout_gravity="start"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="171dp"
android:id="#+id/img_drawer"
android:scaleType="centerCrop"
android:src="#drawable/photo_4"/>
<ListView
android:id="#+id/list_slidermenu"
android:layout_below="#id/img_drawer"
android:layout_width="304dp"
android:listSelector="#drawable/list_selector"
android:checkable="true"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:dividerHeight="1dp"
android:theme="#style/ThemeOverlay.AppCompat.Light"
android:background="#android:color/white" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
Drawer Activity :
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.SpannableString;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
public class DrawerActivity extends ActionBarActivity {
Toolbar t;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private RelativeLayout mRelativeLayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle,mTitle;
private String[] navMenuItems;
private SpannableString[] navmenuItems;
private ArrayAdapter<SpannableString> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
t=(Toolbar)findViewById(R.id.mytoolbardrawer);
setSupportActionBar(t);
initStuffs();
if (savedInstanceState == null) {
new SliderMenuClickListener().displayView(0);
}
}
private void initStuffs() {
mTitle=mDrawerTitle=getTitle();
navMenuItems=getResources().getStringArray(R.array.Titles);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList=(ListView)findViewById(R.id.list_slidermenu);
mRelativeLayout=(RelativeLayout)findViewById(R.id.rel_drawer);
navmenuItems=new SpannableString[navMenuItems.length];
for(int i=0;i<navMenuItems.length;i++) {
navmenuItems[i] = new SpannableString(Html.fromHtml("<font color='#000000'>" + navMenuItems[i] + "</font>"));
}
adapter=new ArrayAdapter<SpannableString>(DrawerActivity.this,android.R.layout.simple_list_item_1,navmenuItems);
mDrawerList.setAdapter(adapter);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle=new ActionBarDrawerToggle(DrawerActivity.this,mDrawerLayout,t,R.string.app_name,R.string.app_name){
public void onDrawerClosed(View view){
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View view){
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setOnItemClickListener(new SliderMenuClickListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.drawer, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen=mDrawerLayout.isDrawerOpen(mRelativeLayout);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mTitle=title;
getSupportActionBar().setTitle(mTitle);
}
#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.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class SliderMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
displayView(position);
}
private void displayView(int position) {
Fragment fragment=null;
switch (position){
case 0:
fragment=new HomeFragment();
break;
case 1:
fragment=new HomeFragment();
break;
case 2:
fragment=new HomeFragment();
break;
case 3:
fragment=new HomeFragment();
break;
default:break;
}
if(fragment!=null){
FragmentManager fm=getSupportFragmentManager();
fm.beginTransaction().replace(R.id.frame_container,fragment).commit();
mDrawerList.setItemChecked(position,true);
mDrawerList.setSelection(position);
setTitle(navMenuItems[position]);
mDrawerLayout.closeDrawer(mRelativeLayout);
}else{
Log.e("DrawerActivity","Error creating fragment");
}
}
}
}