Android: change title in ActionBar from Navigation Drawer - android

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));
}
//==============================================================================
}
//------------------------------------------------------------------------------
}

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

Why Sliding Menu Can't Close in Android

Please I have a problem, in my code like its nothing wrong, why when I select content on Sliding Menu, Sliding menus are not automatically covered? What's wrong with my code? I do not use a fragment only uses a switch to display the menu
MainActivity.java
public class MainActivity extends FragmentActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mDrawerItems = getResources().getStringArray(R.array.list);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer oepns
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// Add items to the ListView
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mDrawerItems));
// Set the OnItemClickListener so something happens when a
// user clicks on an item.
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Set the default content area to item 0
// when the app opens for the first time
if(savedInstanceState == null) {
navigateTo(0);
}
}
/*
* If you do not have any menus, you still need this function
* in order to open or close the NavigationDrawer when the user
* clicking the ActionBar app icon.
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Intent i = new Intent(MainActivity.this, tentang.class);
startActivity(i);
}
if(mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/*
* When using the ActionBarDrawerToggle, you must call it during onPostCreate()
* and onConfigurationChanged()
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private class DrawerItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.v(TAG, "ponies");
navigateTo(position);
}
}
private void navigateTo(int position) {
Log.v(TAG, "List View Item: " + position);
switch(position) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
sejarah.newInstance(),
sejarah.sejarah).commit();
break;
case 1:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
pakaian.newInstance(),
pakaian.pakaian).commit();
break;
case 2:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
rumah.newInstance(),
rumah.rumah).commit();
break;
case 3:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
senjata.newInstance(),
senjata.senjata).commit();
break;
case 4:
Intent i = new Intent(MainActivity.this, lagu.class);
startActivity(i);
break;
case 5:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
musik.newInstance(),
musik.musik).commit();
break;
case 6:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
kesenian.newInstance(),
kesenian.kesenian).commit();
break;
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
}
you miss the the part drawer.closeDrawer(mDrawerList) or mDrawerLayout.closeDrawer(mDrawerList)

The method getSupportFragmentManager() is undefined for the type Context

The error The method getSupportFragmentManager() is undefined for the type Context occur when i used getSupportFragmentManager() inside my oncreateview.
Different context type reference was used to overcome this error but none of these works:
e.g. globalContext = container.getContext(); globalContext = getActivity().getApplicationContext();
getSupportFragmentManager() can be set only in FragmentActivity. My question is if there is a way to reference getSupportFragmentManager().
My fragment.
public class HomeFragment extends Fragment implements
ActionBar.TabListener {
public HomeFragment(){}
Context globalContext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
globalContext = this.getActivity();
actionBar = getActivity().getActionBar();
android.support.v4.app.FragmentManager fm = globalContext.getSupportFragmentManager(); // getting error The method getSupportFragmentManager() is undefined for the type Context }}
mAdapter = new TabsPagerAdapter(fm);
}
}
}
the tabhostlistner adapter.
import android.support.v4.app.FragmentManager;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}}
This is my fragment activity
=====================================
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private boolean isDrawerOpen = false;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// TODO Auto-generated method stub
if(slideOffset > .55 && !isDrawerOpen){
onDrawerOpened(drawerView);
isDrawerOpen = true;
} else if(slideOffset < .45 && isDrawerOpen) {
onDrawerClosed(drawerView);
isDrawerOpen = false;
}
super.onDrawerSlide(drawerView, slideOffset);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
menu.findItem(R.id.itmFavorite).setVisible(!isDrawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#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);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
1) Create the member variable:
private FragmentActivity context;
2) Override the onAttach method of your fragment:
#Override
public void onAttach(Activity activity) {
context = (FragmentActivity) activity;
super.onAttach(activity);
}
3) Get the support FragmentManager like this:
FragmentManager fm = context.getSupportFragmentManager();
In Kotlin
bottomSheetDialogFragment.show((context as FragmentActivity).supportFragmentManager,
bottomSheetDialogFragment.tag)
I am 100% sure that you are not importing the right package for the support Fragment class
make sure that your Fragment import in your HomeFragment look like this:
import android.support.v4.app.Fragment;
you can access Fragment manager in your getView method like below
((Activity)context).getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
where context is an activity ref passed in adapter class
like
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects)
{
super(context, resource, objects);
this.context = context;
}
so fragment manager can be accessed for ex. FragmentManager fm = ((Activity)context).getFragmentManager();

Android ActionBarCompat - Navigation Drawer with multiple fragments

Im new to the ActionBarCompat library.I want to develop an app which contains multiple fragments. Here is what i want to do
1.How to open a fragment when user select that from Navigation Drawer.
2.How to set a startup fragment which displays startup layout (example- In Google plus app,first its displays news feeds.when we select profile item from the side menu,then its hide the side menu/Navigation drawer and displays the profile layout)
Currently i have side menu and one fragment.
Here is the tutorial that i used to follow- wptrafficanalyzer
If you are going to use a slide out menu I recommend you use this slidemenu library I use it in my applications and it allows you to place whatever you want in the slide out menu, the menu is just a frame layout and you can put whatever you want in it (Listview, GridView, or even just a picture)
I am assuming by side menu you meant Navigation Drawer. You can find an answer in the below link.
Navigation Drawer with backword compatibility android
Do read
http://developer.android.com/design/patterns/navigation-drawer.html
Fragment is hosted by a Activity. So you need a container in the activity 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">
<FrameLayout // container to which you add or replace fragments
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"/>
</android.support.v4.widget.DrawerLayout>
Initially you don't click any item. So initially add fragment1 to the container.
FragmentTransaction fragTran = getSupportFragmentManager()
.beginTransaction();
Fragment fragment1= new Fragment1();
fragTran.add(R.id.content_frame, fragment1);
fragTran.commit();
On click of listitem based on the position
FragmentTransaction fragTran = getSupportFragmentManager()
.beginTransaction();
Fragment fragment3= new Fragment3();
fragTran.replace(R.id.content_frame, fragment3);
fragTran.commit();
Hi check this code
public class MainActivity extends ActionBarActivity implements
OnItemClickListener {
DrawerLayout options_drawer;
FrameLayout main_frame;
ListView slider_list;
ActionBar action;
ActionBarDrawerToggle toggler;
BluetoothAdapter blue_adapter;
String options[] = { "Chat", "Device List", "Settings", "Emojis",
"Terms&Conditions" };
Fragment f;
private static final int REQUEST_ENABLE_BT = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
// setSupportProgressBarIndeterminateVisibility(true);
action = getSupportActionBar();
action.setHomeButtonEnabled(true);
action.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
options_drawer = (DrawerLayout) findViewById(R.id.drawer);
main_frame = (FrameLayout) findViewById(R.id.main_frame);
slider_list = (ListView) findViewById(R.id.slider_list);
blue_adapter = BluetoothAdapter.getDefaultAdapter();
if (blue_adapter == null) {
Toast.makeText(getApplicationContext(),
"NO BLUETOOTH DEVICE FOUND", Toast.LENGTH_LONG).show();
finish();
}
ArrayAdapter<String> al = new ArrayAdapter<String>(
getApplicationContext(), R.layout.option_text, options);
slider_list.setAdapter(al);
slider_list.setOnItemClickListener(this);
/*
* toggler=new ActionBarDrawerToggle(MainActivity.this,
* options_drawer,R.
* drawable.ic_launcher,R.string.app_name,R.string.app_name){
*
* #Override public void onDrawerOpened(View drawerView) { // TODO
* Auto-generated method stub super.onDrawerOpened(drawerView);
* options_drawer.openDrawer(slider_list); }
*
* };
*/
// options_drawer.setDrawerListener(toggler);
if (savedInstanceState == null) {
f = new chat_fragment();
fragmentTransition(f);
}
}
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!blue_adapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (item.getItemId() == android.R.id.home) {
// If the drawer is open, close it; vice versa
if (options_drawer.isDrawerOpen(slider_list)) {
options_drawer.closeDrawer(slider_list);
} else {
options_drawer.openDrawer(slider_list);
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
options_drawer.closeDrawer(slider_list);
switch (position) {
case 0:
f = new chat_fragment();
fragmentTransition(f);
break;
case 1:
f = new device_list_fragment();
fragmentTransition(f);
break;
}
}
private void fragmentTransition(Fragment f2) {
// TODO Auto-generated method stub
FragmentTransaction fx = getSupportFragmentManager().beginTransaction();
fx.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fx.replace(R.id.main_frame, f2).commit();
}
}
And XML file is
<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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/main_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<ListView
android:id="#+id/slider_list"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffffff" >
</ListView>
try this link
http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
android actionbarcompat is supported library for below android versions.In this you should do some modifications in code.I am giving some sample code with supported library
code:
public class SliderScreen extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
int checkboxValue=0;
// nav drawer title
private CharSequence mDrawerTitle;
private int selectedPosition=0;
private int currentpos=0;
// used to store app title
private CharSequence mTitle;
ProgressDialog progress_dialog;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
public static String letter = "";
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
ActionBarActivity activity;
MDatabase mdatabaseHelper;
String contact_id = "";
Cursor contactsCursor = null, databaseCursor = null,
messageDatabaseCursor = null,imageDatabaseCursor=null;
String contactCursorValue = "0";
int contactCursorRead = 0, messageCursorRead = 0,imageCursorRead=0;
int messageProgressValue = 0, contactProgressValue = 0,imageProgressValue=0;
AlertDialog d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_screen);
mTitle = mDrawerTitle = getTitle();
// activity=(ActionBarActivity) Context.getApplicationContext();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
progress_dialog = new ProgressDialog(SliderScreen.this);
progress_dialog.setMessage("please wait ");
Builder build=new Builder(SliderScreen.this);
build.setTitle("");
build.setMessage("Do you want to signout ? ");
build.setPositiveButton("Yes",new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
build.setNegativeButton("No",new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
d.dismiss();
}
});
d=build.create();
// Database retrieval
mdatabaseHelper = new MDatabase(SliderScreen.this, null, null, 1);
mdatabaseHelper.getWritableDatabase();
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1), true, 0));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1), true, 0));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1), true,0));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
.getResourceId(4, -1), true, getMusicFilesCount()));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
.getResourceId(5, -1)));
// What's hot, We will add a counter here
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.listbulletes, // nav menu toggle icon
0, // nav drawer open - description for accessibility
0 // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
if(currentpos!=selectedPosition)
{
currentpos=selectedPosition;
displayView(selectedPosition);
}
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
// ActivityCompat.invalidateOptionsMenu(getParent());
// invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(1);
}
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(currentpos!=position)
{
Fragment fragment=new DefaultFragment();
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(" ");
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
selectedPosition=position;
mDrawerLayout.closeDrawer(mDrawerList);
/*
// display view for selected nav drawer item
if(selectedPosition==position)
{
mDrawerLayout.closeDrawer(mDrawerList);
}
else
{
displayView(position);
selectedPosition=position;
}
*/}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new ContactsFragment();
break;
case 2:
fragment = new MessagesFragment();
break;
case 3:
fragment = new ImageFragment();
break;
case 4:
fragment = new MusicFragment();
break;
case 5:
fragment = new SettingsFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
private void showProgressDialog() {
progress_dialog.show();
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#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);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}

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