Android - Adding side navigator from template - android

I have an existing app to which I would like to add a side navigator.
I realized that Android SDK provides a template for that (by adding side navigation drawer activity from the Add menu) but not sure about how to add it the app.
Here is the code of the sidebar class was generated:
package com.testapp;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
public class SideNavActivity extends Activity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_side_nav);
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.side_nav, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_side_nav,
container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((SideNavActivity) activity).onSectionAttached(getArguments()
.getInt(ARG_SECTION_NUMBER));
}
}
}
and here is the code of one of the activities I have:
public class MainMenu extends SideNavActivity implements IResponsable{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main_menu);
final Button btnLogout = (Button) findViewById(R.id.btn_logout);
final Button btnProfile= (Button) findViewById(R.id.btn_prfile);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new HttpGet(HttpClient.getClient(), MainMenu.this).execute("auth/logout");
}
});
btnProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent prof = new Intent(MainMenu.this, ProfileActivity.class);
startActivity(prof);
//finish();
}
});
}
#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, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void getResponse(Object iResult) {
int code = Utils.ParseResponse.getResponseCode((Response)iResult);
if(code == 200)
{
SaveSharedPreference.clearUserName(getApplicationContext());
Intent menu = new Intent(MainMenu.this, LoginActivity.class);
startActivity(menu);
finish();
}
else if(code == 403){
SaveSharedPreference.clearUserName(getApplicationContext());
Intent menu = new Intent(MainMenu.this, LoginActivity.class);
menu.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(menu);
finish();
}
}
}
It also generated simple valid xml files.
When adding this activity in a new blank project, it works fine.
Thank you so much for the assistance!!

With introduction of Android Design Library, the navigation drawer has been reworked and here you will find awesome explanation how now it works:
http://android-developers.blogspot.com/2015/05/android-design-support-library.html
Also there is a sample project created by guys from Google:
https://github.com/chrisbanes/cheesesquare
Take a look at setupDrawerContent method here:
https://github.com/chrisbanes/cheesesquare/blob/master/app/src/main/java/com/support/android/designlibdemo/MainActivity.java#L111
and relevant layout file here:
https://github.com/chrisbanes/cheesesquare/blob/master/app/src/main/res/layout/activity_main.xml

Related

FragmentActivity error Android Studio

Hi i am creating an activity with 4 selection in drawerlayout. Once the user select, a fragment will appear.
First I use Fragment and it run but when I try to convert it into FragmentActivity, i got an error on this line -
fragmentManager.beginTransaction().replace(R.id.main_fragment_container,
fragment).commit();
private void selectItemFragment(int position){
FragmentActivity fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch(position) {
default:
case 0:
fragment = new FragmentDoctor();
break;
case 1:
fragment = new FragmentHospital();
break;
case 2:
fragment = new FragmentPharmacy();
break;
case 3:
fragment = new FragmentClinic();
break;
}
fragmentManager.beginTransaction().replace(R.id.main_fragment_container, fragment).commit();
FRAGMENT DOCTOR
public class FragmentDoctor extends FragmentActivity {
GoogleMap map;
public FragmentDoctor() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_doctor);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null){
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (map != null){
setUpMap();
}
}
}
private void setUpMap() {
map.setMyLocationEnabled(true);
}
MAIN ACTIVITY
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
String[]titles = {"Doctor", "Hospital", "Pharmacy", "Specialty Clinic"};
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private ActionBarDrawerToggle mDrawerToggle;
private Toolbar topToolBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = " ";
topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
topToolBar.setLogo(R.drawable.logo);
topToolBar.setLogoDescription(" ");
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
LayoutInflater inflater = getLayoutInflater();
List<ItemObject> listViewItems = new ArrayList<ItemObject>();
listViewItems.add(new ItemObject("Doctor", R.drawable.icon_doctor));
listViewItems.add(new ItemObject("Hospital", R.drawable.icon_hospital));
listViewItems.add(new ItemObject("Pharmacy", R.drawable.icon_pharmacy));
listViewItems.add(new ItemObject("Specialty Clinic", R.drawable.icon_clinic));
//FIRST FRAGMENT AFTER SPLASH SCREEN
selectItemFragment(0);
mDrawerList.setAdapter(new CustomAdapter(this, listViewItems));
mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(null);
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(null);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItemFragment(position);
}
});
}
private void selectItemFragment(int position){
Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch(position) {
default:
case 0:
fragment = new FragmentDoctor();
break;
case 1:
fragment = new FragmentHospital();
break;
case 2:
fragment = new FragmentPharmacy();
break;
case 3:
fragment = new FragmentClinic();
break;
}
fragmentManager.beginTransaction().replace(R.id.main_fragment_container, fragment).commit();
mDrawerList.setItemChecked(position, true);
setTitle(null);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(null);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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 onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
#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;
}
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
IMPORTS IN MAIN ACTIVITY
android.content.res.Configuration;
android.support.v4.app.Fragment;
android.support.v4.app.FragmentManager;
android.support.v4.widget.DrawerLayout;
android.support.v7.app.ActionBarActivity;
android.support.v7.app.ActionBarDrawerToggle;
android.os.Bundle;
android.support.v7.widget.Toolbar;
android.view.LayoutInflater;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.widget.ListView;
FragmentDoctor should extend from Fragment not from FragmentActivity
change this code
public class FragmentDoctor extends FragmentActivity {
like this
public class FragmentDoctor extends Fragment {
and
private void selectItemFragment(int position){
FragmentActivity fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch(position) {
default:
case 0:
fragment = new FragmentDoctor();
break;
case 1:
fragment = new FragmentHospital();
break;
case 2:
fragment = new FragmentPharmacy();
break;
case 3:
fragment = new FragmentClinic();
break;
}
if(fragment != null) {
fragmentManager.beginTransaction().
replace(R.id.main_fragment_container, fragment).commit();
}
As below
import android.support.v4.app.FragmentActivity;
FragmentActivity is part of support-v4 library..
So please add below dependency to your gradle file :
compile 'com.android.support:support-v4:23.0.1'
You can also add this library by following below steps in Android Studio :
Select File
Select Project Structure
Select app
Select dependencies
Click on '+'
Select library dependency
Select support v4 library and
Press 'OK'
Edited :
public class FragmentDoctor extends FragmentActivity {
And also From your edited code I have noticed that you are extending FragmentActivity not Fragment.
So please follow below link for more information on How to create Fragment with FragmentActivity :
http://www.codepuppet.com/2013/10/06/using-fragments-in-android-with-fragmentactivity/
Thanks

android navigation drawer fragment and ActionBarActivity

I have a navigation drawer and in one of the fragments, I'm trying to add a tab swipe layout. However I am unable to extend both ActionBarActivity and Fragment. Everything I've found online talks about FragmentActivity and not Fragment.
Is their a way to accomplish this?
This is my MainActivity :
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch(position){
case 0:
objFragment = new myPantry_fragment();
break;
case 1:
objFragment = new myRecipes_fragment();
break;
case 2:
objFragment = new wheel_fragment();
break;
case 3:
objFragment = new addRecipes_fragment();//this causes errors
//when I change extends Fragment to extends ActionBarActivity
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4: //added this
mTitle = getString(R.string.title_section4);
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
This is my fragment I access from the navigation drawer.
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class addRecipes_fragment extends ActionBarActivity {
View rootview;
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#Nullable
//#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.addrecipes_layout, container, false); //error shows in video too
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR); //
// setContentView(R.layout.activity_main);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager) rootview.findViewById(R.id.pager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getSupportActionBar();
actionBar.setSelectedNavigationItem(position);
}
});
Tab.setAdapter(TabAdapter);
actionBar = getSupportActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
Log.d("selected: ", "onTabSelected at" + "position" + tab.getPosition() + " " + tab.getText());
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
Log.d("Unselected: ", "onTabSelected at" + "position" + tab.getPosition() + " " + tab.getText());
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
Log.d("Reselected: ", "onTabSelected at" + "position" + tab.getPosition() + " " + tab.getText());
}
};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("General").setTabListener(tabListener)); //Android
actionBar.addTab(actionBar.newTab().setText("Add Ingredients").setTabListener(tabListener)); //IOS
actionBar.addTab(actionBar.newTab().setText("Add steps").setTabListener(tabListener)); //Windows
return rootview;
}
}
Keep your addRecipes_fragment extending the Fragment from support lib. Use a Viewpager in the Fragment layout to display the tabs and a custom PagerAdapter to load them using childfragment manager. Check this link.

How to Call Navigation Drawer Fragment from Activity?

I have a Navigation Drawer which is created by Android studio. I Called a Activity from the Navigation Drawer.In that Activity, the navigation drawer is not showing up ?
How can i Call the Navigation Drawer from the below Activity ?
PlayerActivity
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
public class PlayerActivity extends Activity {
private static final int REQ_START_STANDALONE_PLAYER = 1;
private static final int REQ_RESOLVE_SERVICE_MISSING = 2;
private static final String PLAYLIST_ID = "PL5BxbbBpI7r";
public static final String DEVELOPER_KEY = "AIwXEZQLS-U";
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
}
public void Play(View v) {
int startIndex = 0;
int startTimeMillis = 0;
boolean autoplay = true;
boolean lightboxMode = false;
Intent intent = null;
intent = YouTubeStandalonePlayer.createPlaylistIntent(this, DEVELOPER_KEY,
PLAYLIST_ID, startIndex, startTimeMillis, autoplay, lightboxMode);
if (intent != null) {
if (canResolveIntent(intent)) {
startActivityForResult(intent, REQ_START_STANDALONE_PLAYER);
} else {
// Could not resolve the intent - must need to install or update the YouTube API service.
YouTubeInitializationResult.SERVICE_MISSING
.getErrorDialog(this, REQ_RESOLVE_SERVICE_MISSING).show();
}
}
}
private boolean canResolveIntent(Intent intent) {
List<ResolveInfo> resolveInfo = getPackageManager().queryIntentActivities(intent, 0);
return resolveInfo != null && !resolveInfo.isEmpty();
}
}
Navigation.java
public class Navigation extends Activity
implements HomeFragment.OnFragmentInteractionListener, NavigationDrawerFragment.NavigationDrawerCallbacks, NewsFragment.OnFragmentInteractionListener{
#Override
public void onFragmentInteraction(Uri uri) {
}
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mNavigationDrawerFragment = (NavigationDrawerFragment)getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
switch(position){
case 0:
HomeFragment homeFragment = new HomeFragment();
fragmentManager.beginTransaction().replace(R.id.container, HomeFragment.newInstance("",""))
.commit();
break;
case 1:
NewsFragment newsFragment = new NewsFragment();
fragmentManager.beginTransaction()
.replace(R.id.container, NewsFragment.newInstance("",""))
.commit();
break;
case 2:
Intent intent= new Intent(this,PlayerActivity.class);
startActivity(intent);
break;
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.navigation, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_navigation, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((Navigation) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
NavigationDrawer is meant to work with fragments, because the drawer is a fragment itself. You can access that drawer as long as you stay in the same Activity but once you change Activity you can't access to the drawer (Unless you create another instance of the drawer, but then you are missing the whole point of it). In order to accomplish what you want I'd recommend two things.
1) Instead of launching a new Activity make PlayerActivity a fragment.
2) Create a BaseActivity with a drawer and make all your other Activities extend it, that way you only have one single reference to the drawer in your project.
You should use fragment instead of activity! You should have two fragments as default when you create the project. One is for navigation drawer, and the other one is for content. You should replace that content fragment with your new content which you put in second activity..
You need to do the same thing in the PlayerActivity
mNavigationDrawerFragment = (NavigationDrawerFragment)getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
Also put navigation drawer inside R.layout.activity_player.
Like you did in R.layout.activity_navigation

Android: change title in ActionBar from Navigation Drawer

I created an app with Navigation Drawer in BaseActivity. Everything works ok except the change of title in the Action Bar. the title changes for a second but when opening the new activity is shown the original title.
What can be the error? thanks
BaseActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PerfilAdapter.iniciarBaseDatos(this);
perfilObj = PerfilAdapter.selectPerfil(1);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
cargarActionBar();
cargarDrawerLayout(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.menuOpcSonidos:
...
return true;
case R.id.menuOpcCambiarColor:
...
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.menuOpcSonidos)
.setTitle(getResources().getString(R.string.sonidoOnOff) + " " + perfilObj.getSonidos());
return super.onPrepareOptionsMenu(menu);
}
private void cargarActionBar() {
ActionBar actionBar = getActionBar();
int[] colores2 = Modulo.cargarColoresDrawerlayout(perfilObj.getColor());
actionBar.setBackgroundDrawable(new GradientDrawable(Orientation.BOTTOM_TOP, colores2));
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
int titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView textoTitulo = (TextView)findViewById(titleId);
textoTitulo.setTextColor(getResources().getColor(R.color.blanco));
textoTitulo.setTypeface(null, Typeface.BOLD);
textoTitulo.setTextSize(19);
textoTitulo.setShadowLayer(5, 0, 0, getResources().getColor(R.color.negro));
}
private void cargarDrawerLayout(Bundle b) {
mTitle = mDrawerTitle = getTitle();
textosMenuLateral = getResources().getStringArray(R.array.nav_drawer_items);
iconosMenuLateral1 = getResources()
.obtainTypedArray(R.array.iconos_menu_lateral1);
iconosMenuLateral2 = getResources()
.obtainTypedArray(R.array.iconos_menu_lateral2);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenuMain);
int[] colores = {0, 0xFFFFFFFF, 0};
mDrawerList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colores));
mDrawerList.setDividerHeight(4);
navDrawerItems1 = new ArrayList<DrawerItem>();
navDrawerItems1.add(new DrawerItem(textosMenuLateral[0], iconosMenuLateral1.getResourceId(0, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[1], iconosMenuLateral1.getResourceId(1, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[2], iconosMenuLateral1.getResourceId(2, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[3], iconosMenuLateral1.getResourceId(3, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[4], iconosMenuLateral1.getResourceId(4, -1)));
navDrawerItems2 = new ArrayList<DrawerItem>();
navDrawerItems2.add(new DrawerItem(textosMenuLateral[0], iconosMenuLateral2.getResourceId(0, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[1], iconosMenuLateral2.getResourceId(1, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[2], iconosMenuLateral2.getResourceId(2, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[3], iconosMenuLateral2.getResourceId(3, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[4], iconosMenuLateral2.getResourceId(4, -1)));
iconosMenuLateral1.recycle();
iconosMenuLateral2.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
adapter = new DrawerListAdapter(getApplicationContext(),
navDrawerItems1,
navDrawerItems2,
perfilObj.getColor(),
pos);
mDrawerList.setAdapter(adapter);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.icono_drawer,
R.string.app_name,
R.string.app_name
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (b == null) {
opcionesPanelLateral(0);
}
}
private class SlideMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView textView = (TextView) view.findViewById(R.id.title);
textView.setTypeface(null, Typeface.BOLD);
opcionesPanelLateral(position);
}
}
private void opcionesPanelLateral(int position) {
Intent i;
switch (position) {
case 0:
pos = 0;
break;
case 1:
i = new Intent(this, ActivitySecond.class);
mDrawerLayout.closeDrawer(mDrawerList);
startActivity(i);
pos = 1;
break;
case 2:
i = new Intent(this, ActivityThird.class);
mDrawerLayout.closeDrawer(mDrawerList);
startActivity(i);
pos = 2;
break;
case 3:
i = new Intent(this, ActivityFourth.class);
mDrawerLayout.closeDrawer(mDrawerList);
startActivity(i);
pos = 3;
break;
case 4:
break;
default:
break;
}
mDrawerList.setItemChecked(pos, true);
mDrawerList.setSelection(pos);
setTitle(textosMenuLateral[pos]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
cargarActionBar();
cargarDrawerLayout(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void onBackPressed() {
mDrawerLayout.closeDrawer(mDrawerList);
}
I think that error is the use the Activities... but I don't know as fix
Android Studio allows to add a navigation drawer to the app through File | New | Activity. This "ready-made" navigation drawer comes with everything you need: properties, methods, events, etc.
Next steps to change titles for different fragments are intended to use with the ready-made navigation drawer of Android Studio, but they might be helpful to anyothers:
The navigation drawer has several files : one activity, and one or
more fragments. Open the java activity file of your navigation drawer (what
you call "Base Activity").
Find method onCreate.
In this method, add the line mTitle = "???", where "???" is the title of
the first fragment that will me shown as soon as the navigation drawer
screen appears.
Now find method onNavigationDrawerItemSelected. CHARLIE, I'm not sure,
but I believe you have it under the name opcionesPanelLateral.
In this method you have a switch. This switch opens the appropiate
fragment depending on the selected option. To set the title for each
fragment, go to each case in the switch an add the line mTitle = "My
title"; before frg = new my_frag();. This way, when the fragment opens
it will show the appropiate title.
Find method restoreActionBar. CHARLIE, I don't see it in your code
nor any equivalent method. Add it. Inside of it, add the line
actionBar.setTitle( mTitle);, and here is where the title is actually
set (maybe that's why your title disappears). Call this method inside
onCreateOptionsMenu (after inflate).
That's it. I'm using hard-coded strings, if you follow Android rules, use strings.xml.
Now a real life example from and app I'm working on right now. Next is the raw code of my "BaseActivity" of the ready-made navigation drawer (some things are in spanish because I'm costarrican):
package my_package;
//------------------------------------------------------------------------------
import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
//------------------------------------------------------------------------------
public class menu_act extends ActionBarActivity
implements drawer_frg.NavigationDrawerCallbacks {
//------------------------------------------------------------------------------
// Fragment managing the behaviors, interactions and presentation of the navigation drawer.
private drawer_frg mNavigationDrawerFragment;
// Used to store the last screen title. For use in {#link #restoreActionBar()}.
private CharSequence mTitle;
//------------------------------------------------------------------------------
#Override
protected void onCreate ( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setContentView( R.layout.menu_lay );
mNavigationDrawerFragment = (drawer_frg) getSupportFragmentManager().findFragmentById(
R.id.navigation_drawer );
mTitle = "Perfil"; // getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp( R.id.navigation_drawer,( DrawerLayout )
findViewById( R.id.drawer_layout ) );
// BARRA DE TÍTULO ANARANJADA.
//ActionBar actionBar = getSupportActionBar();
//actionBar.setBackgroundDrawable( new ColorDrawable( getResources().getColor( R.color.col_nar ) ) );
}
//------------------------------------------------------------------------------
#Override
public void onNavigationDrawerItemSelected ( int position ) {
Fragment frg;
// getSupportActionBar().setDisplayOptions( ActionBar.DISPLAY_SHOW_CUSTOM );
switch ( position )
{ case 0 : //getSupportActionBar().setCustomView( R.layout.perfil_tit );
mTitle = "Perfil";
frg = new perfil_frg();
break;
case 1 : // getSupportActionBar().setCustomView( R.layout.contactos_tit );
mTitle = "Contactos";
frg = new contactos_frg();
break;
default : frg = PlaceholderFragment.newInstance( position + 1 );
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace( R.id.container,frg ).commit();
}
//------------------------------------------------------------------------------
public void onSectionAttached ( int number ) {
switch (number) {
case 1 : mTitle = getString( R.string.mnu_opc_per ); break;
case 2 : mTitle = getString( R.string.mnu_opc_con ); break;
case 3 : mTitle = getString( R.string.mnu_opc_sal ); break;
}
}
//------------------------------------------------------------------------------
public void restoreActionBar () {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode( ActionBar.NAVIGATION_MODE_STANDARD );
actionBar.setDisplayShowTitleEnabled( true );
actionBar.setTitle( mTitle );
}
//------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if ( ! mNavigationDrawerFragment.isDrawerOpen() )
{ // Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate( R.menu.menu_act,menu );
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu( menu );
}
//------------------------------------------------------------------------------
#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;
*/
//mDrawerToggle.syncState();
return super.onOptionsItemSelected( item );
}
//==============================================================================
// A placeholder fragment containing a simple view.
public static class PlaceholderFragment extends Fragment {
//------------------------------------------------------------------------------
// The fragment argument representing the section number for this fragment.
private static final String ARG_SECTION_NUMBER = "section_number";
//------------------------------------------------------------------------------
// Returns a new instance of this fragment for the given section number.
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
//------------------------------------------------------------------------------
public PlaceholderFragment() {
}
//------------------------------------------------------------------------------
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_frg, container, false);
return rootView;
}
//------------------------------------------------------------------------------
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((menu_act) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER));
}
//==============================================================================
}
//------------------------------------------------------------------------------
}

How to get items in Navigation Drawer to change view

I want to make an simple app with a Navigation Drawer, which can open other views (News, Information, Gallery, Contact etc). So I opened up the latest Android Studio, made a new project that is compatible with API8>API19, to get maximum reach.
I chose the preset Navigation Drawer and clicked finish. I have figured out to change the names of the items in the Navigation Drawer, but how do I get these items to redirect to a new view?
I have tried implementing the setOnItemClickListener into the MainActivity as the Navigation Drawer site says on http://developer.android.com. But I can't seem to figure out how it all ties together, and it wont work.
tl;dr: I need help with making the items in the Navigation Drawer launch a new view/fragment, and probably an explanation on how it all works.
Here is the app project (Android Studio) https://www.dropbox.com/s/qfz9oul62dzt3rr/NTI_SHOWCASE.zip
MainActivity.java
package com.christianarne.ntishowcase;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private static final int SETTINGS_RESULT = 1;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.rgb(0, 153, 204))); // set your desired color
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
if (id == R.id.action_example) {
Intent intent_g = new Intent(this, Guide.class);
startActivity(intent_g);
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
Would it be better and easier to create an app with the Navigation Drawer from scratch, rather than using a pre-built?
Help is much appreciated.
Well, I'll left this here in case someone needs help switching Fragments in an "Android Studio" Navigation Drawer project
The answer proposed by user2511882, uses the following:
fragment = new FirstFragment();
But the code generated by "Android Studio" uses:
fragment = FirstFragment.newInstance();
(which is a better practice; see why HERE)
That's why his answer doesn't work for your project.
In your case, you have to use something like:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = FirstFragment.newInstance(position + 1);
break;
case 1:
fragment = SecondFragment.newInstance(position + 1);
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
In "Android Studio" it is also a good practice to read the comments and "TODOS" incorporated in the auto generated code.
best regards.
You will need to setup a setOnItemClickListener on your drawerLayout(the id of the listview in your xml file)
Example:
drawerLayout.setOnItemClickListener(new ListView.onItemClickListener){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
displayView(position);
}}
private void displayView(int position) {
switch (position) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_layout_id, fragment).commit(); //
And you need to make separate java class for the FirstFragment and SecondFragment with whatever content you need.
get Item position in navigation view you can set first 0th position menu default by
navigationView.getMenu().getItem(0); // default selected menu
displayview(navigationView.getMenu().getItem(0));
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
displayView(menuItem);
return true;
}
});
}
public void displayView(MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
// fragment = new CheeseListFragment();
break;
case R.id.nav_messages:
fragment = new MessageFragment();
break;
}
if(fragment != null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment)
.commit();
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
}
}
get Item position in navigation view you can set first 0th position menu default by
navigationView.getMenu().getItem(0); // default selected menu

Categories

Resources