I have browsed the website for a bit and I can't find an answer to my problem, I am trying to get my Navigation Drawer to switch between activities instead of fragments. I have tried switch statements and all that does is crash the app, I don't know how to get the separate elements of the drawer in order to set them up so that if one is pressed, it will go to this page and if the other is pressed it will go to this page etc etc.
Here's my code,
package com.example.ColeraineTown;
imports...
public class HomeScreen extends Activity {
private String[] drawerListViewItems;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
// 2. App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// 2.1 create ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* 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 */
);
// 2.2 Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
// 2.3 enable and show "up" arrow
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
drawerLayout.closeDrawer(drawerListView);
}
}
}
I have been at this all day, trying to fix it and get it working, but no luck. It took me so long to get the actual drawer working in the first place it would be a shame to see it all gone.
If you guys have the answer to being able to switch between the activities, that would be great!
Suppose you have 5 items (from 0 index to 4), each index identifying an Activity of your project. You can create a method selectItem(int position)to know what drawer item has been chosen by user.
public void selectItem(int position) {
Intent intent = null;
switch(position) {
case 0:
intent = new Intent(this, Activity_0.class);
break;
case 1:
intent = new Intent(this, Activity_1.class);
break;
...
case 4:
intent = new Intent(this, Activity_4.class);
break;
default :
intent = new Intent(this, Activity_0.class); // Activity_0 as default
break;
}
startActivity(intent);
}
Finally, add this method to your DrawerItemClickListener :
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
drawerLayout.closeDrawer(drawerListView);
}
}
It's easier than using Fragments, I think !!!
Related
Sorry, but my question is more complex than what I have asked. I am new to Java and Android, and this whole NavigationDrawer thing is beating me down, but I am determined to figure it out. I downloaded the sample code from Android with nav drawer example, and I have deleted and added minor changes to fit preferences. Basically, using the code provided to me, I cannot figure out how to change to a different activity/fragment. Should I use another fragment like the example has shown or do I need to create a new Java class that extends an intent and create the corresponding xml layout? Once that is determined, do I create a switch case in the fragment class that was created to cycle through its corresponding fragment/activity? Or do I place a switch case in the selectItem() method? I have been working on this same problem for 8 days now and have finally decided to ask for help after exhausting all of my resources. Thanks for any help. Again, I'm not looking for someone to code for me, I only need help in understanding the questions I have asked and where my code will need to be placed.
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] choices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
choices = getResources().getStringArray(R.array.choices_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, choices));
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
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);
}*/
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) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new ChoicesFragment();
Bundle args = new Bundle();
args.putInt(ChoicesFragment.ARG_CHOICES_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(choices[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 toggle
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows its appropriate layout
*/
public static class ChoicesFragment extends Fragment {
public static final String ARG_CHOICES_NUMBER = "planet_number";
public ChoicesFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.image_view_fragment, container, false);
int i = getArguments().getInt(ARG_CHOICES_NUMBER);
String available_choices = getResources().getStringArray(R.array.choices_array)[i];
int imageId = getResources().getIdentifier(available_choices.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(available_choices);
return rootView;
}
}// end ChoicesFragment class
}// end MainActivity
Looking at the code you posted (I can't compile it and try it now), I believe the intention of the sample is to use fragment when a choice is selected on the navigation drawer. Then you would put a case statement in selectItem() to determine which fragment should be shown.
So for example, if you have two choices (say "Show Red Colour" and "Show Blue Colour"), you would create a "RedFragment" class extending "ChoicesFragment", and a "BlueFragment" class extending "ChoicesFragment". Each of them would use their own XML layout. You can then create a fragment object (say "redFragment" and "blueFragment") for each of them in the onCreate() method.
Then, in the selectItem() method, you have a if/case statement to say if position is 0, then you would show the red fragment with:
...
fragmentManager.beginTransaction().replace(R.id.content_frame, redFragment).commit();
...
and similarly for blue fragment.
HTH.
Looks like you have some problem understanding abstraction levels and i will try to help with that.
Activities are entry points for your app, top level. The best approach is to use fragments and not activites, since fragments are at a lower level of abstraction, fragments are just pieces of activities.
Build all of your views in fragments and then put them on an activity, unless you really need a bigger level of abstraction depending on what your application does.
I do not see the need to create a class extending intent, etc. etc.
what i would is to add the navigation drawer as a fragment and put it in an activity, and the rest of the app should be fragments as well handled by the navigation drawer.
Or the navigation drawer can be part of the activity and the rest of the views fragments that depend from this activity.
Hope this helps to clear your mind.. sorry for not sharing code.. good luck
I have one basic question that I couldn't get hold in last couple of days (even after many example/explanation in googling and SOing).
I have 5 different Activity , each activity is independent of others, and each activity has it’s own layout file. Now, I want to add Navigation Drawer as my App Menu.
What i understand, 2 recommended ways are:
1) To merge those 5 activities into one MainActivity, and use 5 fragments to load 5 different layout. But it will be a hard for me to merge those 5 into 1. And won't there be any performance issue if I have all methods loaded in one Activity?
2) To have one BaseActivity containing drawer, and extend all other activity to Base Activity. But I have all my Activities extended to NavDrawer class (which contains drawer), but not working. Individually drawer is working fine (when I run NavDrawer only). Do I need to make any change to the layout xmls of my existing activities?
I am sorry if this is pretty much basic, but I am posting this after I failed to get hold the concept in 2 days!
I can attach my code if you want, but the drawer code is sort of basic thing, as per tutorial.
Thanks,
References I am using:
1) http://developer.android.com/training/implementing-navigation/nav-drawer.html
2) http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
I can suggest you to use ViewPager with actionbar tabs. Because with the help of viewpager, the same navigation draawer is visible for all the five fragments. Coming to the efficiency, ViewPager creates current page, besides it always prepares your next and previous pages also. So that it can be bit fast in showing the content while the user swipes pages. I always follow the same and I don't think it's inefficient.
Code snippet of one of my applications is below:
public class MainActivity extends ActionBarActivity {
String[] titles;
ViewPager viewPager;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mListTitles;
public PagerTabStrip titleStrip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewPager = (ViewPager) findViewById(R.id.pager);
TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
viewPager.setAdapter(titleAdapter);
viewPager.setCurrentItem(0);
mTitle = mDrawerTitle = getTitle();
mListTitles = getResources().getStringArray(R.array.drawerlist_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// sets up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mListTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enables ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
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)
{
getSupportActionBar().setTitle(mTitle);
}
public void onDrawerOpened(View drawerView)
{
getSupportActionBar().setTitle(mDrawerTitle);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null)
{
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
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;
}
else{
return false;
}
}
class TitleAdapter extends FragmentPagerAdapter{
private String titles[] = new String[]{"Expenses","Savings","Income"};
private Fragment frags[] = new Fragment[titles.length];
public TitleAdapter(FragmentManager fm) {
super(fm);
frags[0] = new Fragment1();
frags[1] = new Fragment2();
frags[2] = new Fragment3();
}
#Override
public CharSequence getPageTitle (int position){
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
}
/* 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 selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mListTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#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);
}
}
I've created a BaseActivity for my Drawer but it always crashes on start. I don't know why it alsways crashes. Does anybody know what to do or how to configure the BaseActivity right?
It always crashes in the onCreate and when I configure the drawer. Any ideas?
Code of the BaseActivity :
public abstract class BaseActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
public Context context;
#Override
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
String[] menu = getResources().getStringArray(R.array.menu);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, menu));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_navigation_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) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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 true;
}
/* 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) {
switch (position) {
case 0:
Intent all = new Intent(context, All.class);
startActivity(all);
break;
case 1:
Intent country = new Intent(context, ByCountry.class);
startActivity(country);
break;
case 2:
Intent device = new Intent(context, ByDevice.class);
startActivity(device);
break;
case 3:
Intent about = new Intent(context, About.class);
startActivity(about);
break;
case 4:
Intent info = new Intent(context, Info.class);
startActivity(info);
break;
case 5:
Intent settings = new Intent(context, Settings.class);
startActivity(settings);
break;
}
} };
#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);
}
}
If you're using the ActionBarActivity use getSupportActionBar() insteed of getActionBar().
In your onCreate you don't have any setContentView(int layoutResource) method, so all referenced views are null because they are not found.
I had this issue and i was due to not having a layout in abstracted baseActivity's XML layout.
Just add an empty LinearLayout for instanse to your xml file:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
You are extending ActionBarActivty. Try extending Activity class only.
public abstract class BaseActivity extends Activity {
In my Navigation Drawer I have a problem, when it loads anything in the first spot will crash the app, so my solution to this is to set it to a string that changes to say "(appname) Free" or " (appname) Premium", depending on if the premium upgrade was purchased.
I would like this unclickable as it is currently able to be clicked but nothing happens. Ideally this would be a submenu, or title, but I could not figure out how to implement that. Here is a excerpt of my code:
public class myClass extends SherlockActivity implements
OnItemSelectedListener {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
mTitle = mDrawerTitle = getTitle();
if (mIsPremium == true) {
mPlanetTitles = getResources().getStringArray(
R.array.planets_array_prem);
} else {
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
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().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) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
switch (position) {
case 0:
/*
* Toast.makeText( getApplicationContext(),
* "case 0 - A Activity.", Toast.LENGTH_LONG).show(); Intent
* c0 = new Intent(getBaseContext(),
* activity.class); startActivity(c0);
*/break;
case 1:
Toast.makeText(getApplicationContext(),
"case 1 - B Activity", Toast.LENGTH_LONG).show();
Intent c1 = new Intent(getBaseContext(),
ActivityB.class);
startActivity(c1);
break;
default:
}
}
}
public void selectItem(int position) {
switch (position) {
case 0:
// setContentView(R.layout.main);
break;
case 1:
setContentView(R.layout.main);
break;
default:
}
}
#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);
}
I do not use fragments, I was going to implement the navigation drawer by doing on click and moving to new activities. I am looking for a solution to my primary problem but would welcome any design tips.
Thank you
Edit
With CommonsWare's help I developed this: but nothing is different in my application. I want the first time (case 0 (position 0)) to be disabled.
public class MyArrayAdapter extends ArrayAdapter<String> {
public MyArrayAdapter(Context context, int position) {
super(context, 0);
}
public boolean areAllItemsEnabled() {
return false;
}
public boolean isEnabled(int position) {
if (position == 0) {
return false;
} else {
return true;
}
}
}
As you already know, since you already read the answer, you need to replace your new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles) with a custom Adapter -- perhaps one extending ArrayAdapter<String> -- where you override areAllItemsEnabled() to return false and isEnabled() to return true or false as needed.
See also:
android - disable listview item click and reenable it
Android ListView child View setEnabled() and setClickable() do nothing
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/>