Custom navigation drawer with activity & fragment - android

This is the code of the main activity, that contains a lateral menu with three button, what that i want to do is :
Modify this code and replace the action in the "listener" of the buttons in lateral menu, now when i press a button, a new fragment is created, but i want create a new activity (NOT a fragment), maintaining the layout (lateral menu).
How i can do this ?
public class MainActivity extends Activity {
// declare properties
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for proper titles
mTitle = mDrawerTitle = getTitle();
// initialize properties
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// list the drawer items
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[3];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_copy, "Create");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_refresh, "Read");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_share, "Help");
// Pass the folderData to our ListView adapter
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
// Set the adapter for the list view
mDrawerList.setAdapter(adapter);
// set the item click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// for app icon control for nav drawer
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// to change up caret
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
// navigation drawer click listener
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CreateFragment();
break;
case 1:
fragment = new ReadFragment();
break;
case 2:
fragment = new HelpFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[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);
}
}
*********** EDIT 1 ***********
I try this method:
I replace this part :
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CreateFragment();
break;
case 1:
fragment = new ReadFragment();
break;
case 2:
fragment = new HelpFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
with this:
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
break;
case 1:
Intent intent = new Intent(this, MyCustomActivity.class);
startActivity(intent)
break;
case 2:
Intent intent2 = new Intent(this, MyCustomActivity.class);
startActivity(intent2)
break;
default:
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
But when i try on my device, the button doesn'n work as if I had not binded action
*********** EDIT 2 ***********
public class MainActivity extends Activity implements View.OnClickListener {
// declare properties
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for proper titles
mTitle = mDrawerTitle = getTitle();
// initialize properties
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// list the drawer items
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[3];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_copy, "Create");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_refresh, "Read");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_share, "Help");
// Pass the folderData to our ListView adapter
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
// Set the adapter for the list view
mDrawerList.setAdapter(adapter);
// set the item click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// for app icon control for nav drawer
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// to change up caret
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
// navigation drawer click listener
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public void onClick(View arg0) {
System.out.println("DEBUG"+arg0);
//ACTION, arg0 no value
}
}

Create a new Activity Extending your MainActivity which is having the Navigation Drawer.This new Activity will automatically have the navigation Drawer.
Check this answer for further details :
Same Navigation Drawer in different Activities

Did you try to inflate to a new Activity instead of creating a new Fragment in private void selectItem(int position) { ... } I mean, when you get the position, to create an Intent for the current activity Intent intent = new Intent(this, YourCustomActivity.class); and to navigate to it with startActivity(intent)

Related

Android navigation drawer baseactivity possible with different items?

I find a lot of tutorials on the Internet on how to implement a navigation drawer for Android Studio.
However, let's say I want to create a navigation drawer for any activity but with different items, is it possible to create some sort of baseactivity so I only need to write the NavDrawerItems and the DrawerItemClickListener ...
Can this BaseActivity be achieved or is it too far fetched? I searched alot on Google about this, but didn't find any tutorials concerning this particular question I got :( Most of the baseactivity tutorials I find are for navigation drawer with the same items.
Edit:
Code I have for now, but in my opinion it's a bit long to read:
Tutorials I used are:
https://trinitytuts.com/android-navigation-drawer-with-material-design-arrow/ http://thedeveloperworldisyours.com/android/put-image-navigation-drawer/
public class MainActivity extends Activity {
private Context context;
private RelativeLayout mDrawerRelativeLayout;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mRequestsArray;
Toolbar toolbar;
TextView toolbarTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = this;
mTitle = mDrawerTitle = getTitle();
mRequestsArray = new String[] { "Catalog", "Account", "Checkout", "Utilities"};
mDrawerRelativeLayout = (RelativeLayout) findViewById(R.id.left_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbarTitle = (TextView) findViewById(R.id.titletool);
// 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
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mRequestsArray));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
toolbarTitle.setText(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
toolbarTitle.setText(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
setTitle(getTitle());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#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) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CatalogFragment();
break;
case 1:
fragment = new AccountFragment();
break;
case 2:
fragment = new CheckoutFragment();
break;
case 3:
fragment = new UtilitiesFragment();
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();
}
selectItem(position);
mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
}
}
private void selectItem(int position) {
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mRequestsArray[position]);
mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
toolbarTitle.setText(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);
}
}
In my opinion, it's possible. You can set it when preparing your list data, as the following sample
private static void prepareListData(final Context context) {
final Activity activity = ((Activity) context);
String activity_name = context.getClass().getSimpleName().replace("Activity", "");
sListDataHeader = new ArrayList<>();
sListDataChild = new HashMap<>();
// adding header data, except current activity
String[] mItemHeaders = activity.getResources().getStringArray(R.array.items_array_expandable_header);
// here...
for (String item : mItemHeaders) {
if (!item.toLowerCase().equals(activity_name.toLowerCase())) {
sListDataHeader.add(item);
}
}
String[] mItemMainChild = activity.getResources().getStringArray(R.array.items_array_expandable_main_child);
// Child data
List<String> listChild = Arrays.asList(mItemMainChild);
// Header, Child data
for (int i = 0; i < sListDataHeader.size() - 2; i++) {
sListDataChild.put(sListDataHeader.get(i), new ArrayList<String>());
}
sListDataChild.put(sListDataHeader.get(sListDataHeader.size() - 1), listChild);
}
Hope this help!

Android widget, launch a Fragment?

I currentley have an adroid widget, that when clicked on launches an activity. I have changed my whole app to fragments in order to use the android navigation drawer, and I am not sure how to launch my fragment when my widget is clicked.
My widget code which launches an activity is:
public class SearchWidget extends AppWidgetProvider {
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, Search.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_search);
views.setOnClickPendingIntent(R.id.searchclick, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current app widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
How can I launch a fragment, but also launch it in my view which hold my drawer also?
I have a MainDrawer activity:
public class MainDrawer2 extends Activity {
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 ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0]));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1]));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2]));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3]));
// 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);
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
//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();
}
};
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);
}
}
/**
* 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 StatisticsPage();
break;
case 1:
fragment = new Discover();
break;
case 2:
fragment = new Portfolio();
break;
case 3:
fragment = new NewsWeb();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.main, 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 boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().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.menu_search2:
//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);
}
#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);
}
public void goToSearch(MenuItem item){
//go to search page
//Intent i = new Intent(this,Search.class);
//startActivity(i);
FragmentManager man=getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment Fragment_four= new Search();
tran.replace(R.id.main, Fragment_four);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
The main drawer uses this xml which has a fragment for the navigation drawer and one for the actual fragments that get loaded. The MainDrawer activity above initiates with the statistics fragment. I want my widget to launch with the below xml but not initiate the statistics fragment. I want it to load another fragments.
XML:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<ListView
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#android:color/white"
android:background="#android:color/black"
android:choiceMode="singleChoice"/>
</android.support.v4.widget.DrawerLayout>
UPDATE:
public class MainDrawer2 extends Activity {
public static final String EXTRA_DEFAULT_FRAGMENT = "com.beerportfolio.beerportfoliopro.EXTRA_DEFAULT_FRAGMENT";
public static final int FRAGMENT_STATISTICS = 0;
public static final int FRAGMENT_DISCOVER = 1;
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 ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0]));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1]));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2]));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3]));
// 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);
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
//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();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
Intent i = getIntent();
// Default to the stats fragment if a default wasn't supplied
int defaultView = i.getIntExtra(EXTRA_DEFAULT_FRAGMENT, FRAGMENT_STATISTICS);
displayView(defaultView);
}
}
/**
* 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);
}
}
/**
* 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 StatisticsPage();
break;
case 1:
fragment = new Discover();
break;
case 2:
fragment = new Portfolio();
break;
case 3:
fragment = new NewsWeb();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.main, 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 boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().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.menu_search2:
//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);
}
#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);
}
public void goToSearch(MenuItem item){
//go to search page
//Intent i = new Intent(this,Search.class);
//startActivity(i);
FragmentManager man=getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment Fragment_four= new Search();
tran.replace(R.id.main, Fragment_four);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
So it looks like you already have a good framework in place that'll make this easy. First, define a value for an extra to pass in with your launch intent:
public class MainDrawer2 extends Activity {
public static final String EXTRA_DEFAULT_FRAGMENT = "my.package.name.EXTRA_DEFAULT_FRAGMENT";
public static final int FRAGMENT_STATISTICS = 0;
public static final int FRAGMENT_DISCOVER = 1;
//... etc.
Then, in your onCreate(), where you current call displayView(0), do something like:
if (savedInstanceState == null) {
Intent i = getIntent();
// Default to the stats fragment if a default wasn't supplied
int defaultView = i.getIntExtra(EXTRA_DEFAULT_FRAGMENT, FRAGMENT_STATISTICS);
displayView(defaultView);
}
This way, you can create your PendingIntent with your Activity launch Intent, but when you do so, simply include the default fragment extra:
Intent i = new Intent(context, MainDrawer2.class);
i.putExtra(MainDrawer2.EXTRA_DEFAULT_FRAGMENT, MainDrawer2.FRAGMENT_DISCOVER);
PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0);
Here's an example of doing what you want.
https://docs.google.com/file/d/0BxaaQ-XiIcHAakxVSTZYMURlYm8/

How to make my menu items do something?

I am new in Android world. I have followed this tutorial to create a swipe menu but the items of this menu just show an image. I want to link every single one to a new activity, is this possible?
My main activity:
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
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 opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
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);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#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);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
yes you can do that in onOptionsItemSelected event.
onOptionsItemSelected has a paremeter of type MenuItem . you can see the paremeter here onOptionsItemSelected(MenuItem item).
Just pick item.getTitle and do what you want according to the selected item
Replace OtherActivity.class and anotherActivity.class with your actual activity class names and you are done.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getTitle()=="View 1")
{
Intent newActivity = new Intent(this,OtherActivity.class );
startActivity(newActivity);
}
else
{
Intent newActivity = new Intent(this,anotherActivity.class);
startActivity(newActivity);
}
return MenuChoice(item);
}

Android Navigation Drawer BaseActivity sample

Can someone suggest me a tutorial how to create a BaseActivity for the Android Navigation Drawer ?
Or can anyone post a sample BaseActivity for the Navigation Drawer including the layout ?
Download sample Code from Google n i have edited that code as basic navigation drawer with fragment no imageview
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
Fragment fragment = new PlanetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// mTitle = mDrawerTitle = getTitle();
// mPlanetTitles = getResources().getStringArray(R.array.planets_array);
// mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//mDrawerList = (ListView) findViewById(R.id.right_drawer);
// 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
// mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
// getActionBar().setDisplayHomeAsUpEnabled(true);
// getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, host Activity
mDrawerLayout, DrawerLayout object
R.drawable.ic_drawer, nav drawer image to replace 'Up' caret
R.string.drawer_open, "open drawer" description for accessibility
R.string.drawer_close "close drawer" description for accessibility
) {
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);
if (savedInstanceState == null) {
selectItem(0);
}*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
//#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);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}*/
///#Override
/* public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
if (mDrawerLayout.isDrawerOpen(Gravity.END)==true)
{
mDrawerLayout.closeDrawers();
}else
{
mDrawerLayout.openDrawer(Gravity.END);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}*/
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Toast.makeText(getApplicationContext(), "You Select the Position"+position, Toast.LENGTH_SHORT).show();
Bundle args = new Bundle();
//args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
// fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#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);
}*/
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
// public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.navigation_fragment, container, false);
// int i = getArguments().getInt(ARG_PLANET_NUMBER);
//String planet = getResources().getStringArray(R.array.planets_array)[i];
// int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
// "drawable", getActivity().getPackageName());
// ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
/// getActivity().setTitle(planet);
return rootView;
}
}
}
You can achieve this with the help of fragments. Go through following which have sample code and video tutorial.
http://manishkpr.webheavens.com/android-navigation-drawer-example-using-fragments/
http://developer.android.com/training/implementing-navigation/nav-drawer.html

DrawerLayout on click disabled after first event

I'm trying to implement a drawer layout in my app. I follow the tutorial on android developer site and all goes fine. I have only a "little" problem: I lunch the app, open the drawer layout and click on an element of the list view and all goes great, but when I try to open another time the drawer and click on one of his element I noticed that the element that I've first clicked is still clicked and i'm not able to click on any of the other elements.The drawer simply close without lunching any onClick events.
My code is:
public class Eventi extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.eventi);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.menu);
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
// opens
// mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
// GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.listview_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_launcher, /* nav drawer image to replace 'Up' caret */
R.string.hello_world, /* "open drawer" description for accessibility */
R.string.hello_world /* "close drawer" description for accessibility */
) {
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);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.eventi, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#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);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case R.id.action_settings:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.hello_world, Toast.LENGTH_LONG)
.show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
System.out.println("c2");
selectItem(position);
}
}
private void selectItem(int position) {
System.out.println("c");
final String[] classes = getResources().getStringArray(R.array.classi);
FragmentTransaction tx = getFragmentManager().beginTransaction();
tx.replace(R.id.drawer_layout,
Fragment.instantiate(Eventi.this, classes[position]));
tx.commit();
/*
* // update the main content by replacing fragments Fragment fragment =
* new PlanetFragment(); Bundle args = new Bundle();
* args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
* fragment.setArguments(args);
*
* FragmentManager fragmentManager = getFragmentManager();
* fragmentManager.beginTransaction() .replace(R.id.content_frame,
* fragment).commit();
*/
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#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);
}
}
I took it from the Developer site so I don't understand wher is the error. Is there anyone who can help me?
Thanks in advance ;)
Take a look at my code:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
switch (position) {
case 0:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new MainActivityFragment())
.commit();
break;
case 1:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new DbListViewFragment())
.commit();
break;
case 2:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new StatisticsFragment())
.commit();
break;
case 3:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new CalculatorFragment(), "calculator")
.commit();
break;
}
I am using a switch-case. position 0 is the very first item in my ListView inside the drawer.
The problem is that you are using
FragmentTransaction.replace(r.Id.drawer_layout,fragment).
don't attach a fragment directly to the drawerlayout element , try to add a framelayout as your main content container then attach the fragment to this framelayou.
Your xml content should look like this sudo one
<drawerlayout>
<framelayout Id:fragment_holder/> //attach fragment to this view
<ListView/> // your drawer ListView.
<drawerlayout/>

Categories

Resources