package com.example.jaffer.firstapp;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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 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;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I want it so that the buttons on the navigation drawer take me to an activity instead of a fragment, i tried so many things but couldn't make it work. can someone please help me, it will be greatly appreciated.
Here is an example based off of my comment:
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// some toast
Toast.makeText(MainActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
// some position
if (position == 0) {
startActivity(new Intent(YOUR_ACTIVITY)); // put your activity here
}
}
});
Related
How do i add items on navigation drawer from List<String> minerals = new ArrayList<String>();? is this possible?
navigation view
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/activity_navigation_drawer">
</android.support.design.widget.NavigationView>
main_acitivity.java
package xxxxxxxx;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class loginhome extends AppCompatActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginhome);
Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, R.layout.drawer_items,R.id.label ,osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(loginhome.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_help) {
Toast.makeText(loginhome.this, "setting", Toast.LENGTH_LONG).show();
}
if(id == R.id.action_place){
Toast.makeText(loginhome.this, "Refresh App", Toast.LENGTH_LONG).show();
}
if(id == R.id.action_search){
Toast.makeText(loginhome.this, "Create Text", Toast.LENGTH_LONG).show();
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
drawer_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="30sp"
android:background="#D3D3D3">
</TextView>
</LinearLayout>
I'm trying to create a navigation drawer. I have created it but the problem is that when i open the app the first time, the fragment is displayed in the content area but it is not highlighted in the navigation drawer.
This is code i'm using:
package com.hfad.evenit;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.hfad.evenit.Fragments.FourthFragment;
import com.hfad.evenit.Fragments.SecondFragment;
import com.hfad.evenit.Fragments.ThirdFragment;
import com.hfad.evenit.Fragments.TopFragment;
public class Home extends AppCompatActivity {
String []FragmentTitles;
ListView DrawerList;
DrawerLayout drawerLayout;
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
FragmentTitles = getResources().getStringArray(R.array.fragment_titles);
DrawerList = (ListView) findViewById(R.id.drawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
DrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, FragmentTitles));
DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
selectItem(0);
DrawerList.setSelection(0);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open_drawer, R.string.close_drawer) {
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = drawerLayout.isDrawerOpen(DrawerList);
menu.findItem(R.id.action_share).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if(drawerToggle.onOptionsItemSelected(item))
{
return true;
}
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void selectItem(int position)
{
Fragment fragment;
switch(position)
{
case 0:
fragment = new TopFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
case 3:
fragment = new FourthFragment();
break;
default:
fragment = new TopFragment();
}
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
setActionBarTitle(position);
drawerLayout.closeDrawer(DrawerList);
}
public void setActionBarTitle(int position)
{
String title;
title = FragmentTitles[position];
getSupportActionBar().setTitle(title);
}
}
The method you should use for changing the items state to "highlighted" or currently activated is setItemChecked(int position, boolean value). It's best to place it in your selectItem method so that the "highlighted" item changes once your SelectItem method is called.
You might also want to consider setting the listView's choice mode to CHOICE_MODE_SINGLE so that only one item can be in an active state at a given time.
drawerList.setChoiceMode(CHOICE_MODE_SINGLE);
Around here...
public void selectItem(int position) {
...
setActionBarTitle(position);
drawerLayout.closeDrawer(DrawerList);
}
Adding DrawerList.setItemChecked(position, true); may work.
public void selectItem(int position) {
...
setActionBarTitle(position);
DrawerList.setItemChecked(position, true); // <== add this line
drawerLayout.closeDrawer(DrawerList);
}
Actually I'm not using Navigation Drawer of the Android Studio's project template but using NavigationView (it is recommended for ease to use), recently. If my answer is invalid, please forget this.
I'm trying to create a navigation drawer for Android. I've followed these pages (this and this) but now I'm stuck.
Here's my code, based on the planet navigation drawer:
package com.example.side_navigation_from_scratch;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private String mDrawerTitle;
private String mainTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
mainTitle = mDrawerTitle = (String) getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// 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());
// 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.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mainTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.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);
}
}
/* 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) {
mainTitle = (String) title;
getActionBar().setTitle(mainTitle);
}
/**
* 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];
TextView planetName = (TextView) rootView.findViewById(R.id.text);
getActivity().setTitle(planet);
return rootView;
}
}
}
I get different errors depending on the changes I make.
Like it is right now, I get
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
ActionBarActivity is deprecated so I'm not going to use it but if I change Activity to AppCompatActivity, I get
java.lang.IllegalArgumentException: AppCompat does not support the current theme features
What am I doing wrong? Which is better to use: Activity, ActionBarActivity or AppCompatActivity? Thanks in advance
Thanks to Raghunandan I managed to fix this: I changed the Activity to AppCompatActivity and replaced getActionBar for getSupportActionBar. I don't have any more NPE
I want to share a demo on Navigation Folding Drawer. How do I do it?
I've come across some really pernicious problems where there is either no good information available or the good information is buried under a sea of bad information.
You have to download the Folding Layout library.
import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import com.ptr.folding.FoldingDrawerLayout;
public class DemoActivity extends ActionBarActivity {
private FoldingDrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mAnimalTitles;
private ItemSelectedListener mItemSelectedListener;
static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT == Build.VERSION_CODES.HONEYCOMB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
mTitle = mDrawerTitle = getTitle();
mAnimalTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (FoldingDrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// mFoldLayout = (FoldingNavigationLayout)findViewById(R.id.fold_view);
// mFoldLayout.setBackgroundColor(Color.BLACK);
// 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, mAnimalTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mItemSelectedListener = new ItemSelectedListener();
// 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 */
) {
#SuppressLint("NewApi")
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
if (IS_HONEYCOMB) {
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
}
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#SuppressLint("NewApi")
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
if (IS_HONEYCOMB) {
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
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 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 AnimalFragment();
Bundle args = new Bundle();
args.putInt(AnimalFragment.ARG_ANIMAL_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mAnimalTitles[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 config) {
super.onConfigurationChanged(config);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(config);
}
/**
* Listens for selection events of the spinner located on the action bar.
* Every time a new value is selected, the number of folds in the folding
* view is updated and is also restored to a default unfolded state.
*/
private class ItemSelectedListener implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
int mNumberOfFolds = Integer.parseInt(parent.getItemAtPosition(pos).toString());
mDrawerLayout.getFoldingLayout(mDrawerList).setNumberOfFolds(mNumberOfFolds);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
}
Here's a screen-shot:
So, I have this weird problem: I'm trying to use a DrawerLayout that contains a ListView for the slide-out selection component and a FrameLayout that will contain a specific fragment depending on the ListView item that is clicked. I have scoured the net for answers, I have read books and watched tutorials and I have finally managed to do just that in a way that I finally half-understand: great, you say! Not so fast!
I'm left with a tiny problem though that's making my OCD go crazy: the ic_drawer icon (the three-vertical-lines thing that responds to the sliding out and the sliding in of the drawer) stops responding as soon as I press a ListView item that loads a fragment, ie. it stays in the "drawer opened" position (partially hidden in literal terms). I have tried using the syncState() method in various points in the code but no luck.
The code of the Activity that contains the drawer layout follows. Keep in mind that literally everything else works perfectly - it's just the ic_drawer icon that stops responding to the slide-out and slide-in state of the drawer as soon as I press a listview item and the relevant fragment appears:
package com.example.jsonbourne;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class DrawerActivity extends Activity {
private ActionBarDrawerToggle mDrawerToggle;
private ListView mList;
private DrawerLayout mDrawer;
private String[] listCells1 = { "Profile", "Messages", "Log In", "Register" };
private String[] listCells2 = { "Profile", "Messages", "Log Out" };
final String[] fragments1 = { "com.example.jsonbourne.ProfileFragment",
"com.example.jsonbourne.MessageFragment",
"com.example.jsonbourne.LoginFragment",
"com.example.jsonbourne.RegisterFragment" };
final String[] fragments2 = null;
public void onCreate(Bundle firebug) {
super.onCreate(firebug);
setContentView(R.layout.activity_drawer);
// setting up action bar
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mList = (ListView) findViewById(R.id.listf);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActionBar()
.getThemedContext(), android.R.layout.simple_list_item_1,
listCells1);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawer,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle("title");
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("title");
invalidateOptionsMenu();
}
};
mDrawer.setDrawerListener(mDrawerToggle);
mList.setAdapter(adapter);
mList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int pos, long id) {
mDrawer.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.frame, Fragment.instantiate(
DrawerActivity.this, fragments1[pos]));
ft.commit();
}
});
mDrawer.closeDrawer(mList);
mDrawerToggle.syncState();
}
});
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frame,
Fragment.instantiate(DrawerActivity.this, fragments1[0]));
ft.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onPostCreate(Bundle savedInstanceStates) {
super.onPostCreate(savedInstanceStates);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
/*if (item.getItemId() == android.R.id.home) {
// Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
return true;
}*/
if (item.getItemId() == R.id.something) {
Toast.makeText(this, "Something something", Toast.LENGTH_LONG)
.show();
}
return super.onOptionsItemSelected(item);
}
}
Any ideas? Surprisingly, I haven't found anyone else that has the same problem, even after long Google search sessions.
You're calling DrawerLayout.setDrawerListener twice, but expecting the original one to keep in sync. It looks like you want to swap each Fragment after the DrawerLayout closes. Here's an example to do that with the original ActionBarDrawerToggle you set up in onCreate.
Set up a Fragment variable
private Fragment mFragment;
In onCreate
#Override
public void onDrawerClosed(View view) {
...
if (mFragment != null) {
final FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.frame, mFragment).commit();
}
}
In OnItemClickListener.onItemClick
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
mFragment = yourNewFragmentInstance;
mDrawer.closeDrawer(mList);
}