Fragment not showing icon - java

I'm having trouble with an android app, mainly because when I load a fragment into the activity it never shows the icon in the app (it shows the 3 dots as if there's no space for the icon to show and it displays the text instead).
My activity is using a navigation drawer I don't know if it has to do with the problem, I've read several answers with the same problem but none of the solutions seem to affect the behaviour.
If I add the icon programatically it shows fine, but whenever I try to use the XML it never shows the icon as action.
I'm targeting minSDK = 14 and targetSDK = 19
Here's my main activity
public class MainActivity extends Activity {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
List<DrawerItem> dataList;
CustomDrawerAdapter adapter;
/**
* Used to store the last screen title. For use in {#link #()}.
*/
private CharSequence mTitle;
private CharSequence mDrawerTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close){
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList = (ListView) findViewById(R.id.lvNavigationDrawer);
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//mMenuTitles = getResources().getStringArray(R.array.menu_array);
dataList.add(new DrawerItem("Perfil", R.drawable.ic_perfil));
dataList.add(new DrawerItem("Code Redeemer", R.drawable.ic_coderedeemer));
dataList.add(new DrawerItem("Mi ID", R.drawable.ic_id));
dataList.add(new DrawerItem("Sucursales", R.drawable.ic_sucursales));
dataList.add(new DrawerItem("GP Finder", R.drawable.ic_finder));
dataList.add(new DrawerItem("Calculadora Intercambio", R.drawable.ic_intercambio));
dataList.add(new DrawerItem("Notificaciones", R.drawable.ic_configuracion));
dataList.add(new DrawerItem("ConfiguraciĆ³n", R.drawable.ic_configuracion));
adapter = new CustomDrawerAdapter(this,R.layout.custom_drawer_item, dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
//mDrawerList.setAdapter(new ArrayAdapter<>(this,R.layout.drawer_list_item,mMenuTitles));
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
Fragment content;
// Create a new fragment and specify the planet to show based on position
switch (position){
case 0:
content = new StubFragment();
break;
case 4:
content = new FinderFragment();
break;
default:
content = new FinderFragment();
}
setTitle(dataList.get(position).getItemName());
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.flFragmentContainer, content)
.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(dataList.get(position).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
return mDrawerToggle.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
//Pass any configuration change to the drawer
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
FinderFragment.java
public class FinderFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_finder, container, false);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
/*menu.add(Menu.NONE, /*//** group ID.. not really needed unless you're working with groups **//**//**//**//*
0, /*//** this is the items ID (get this in onOptionsItemSelected to determine what was clicked) **//**//**//**//*
Menu.NONE, /*//** ORDER.. this is what you want to change **//**//**//**//*
R.string.search_product) /*//** title **//**//**//**//*
.setIcon(android.R.drawable.ic_menu_search)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);*/ //THIS WORKS CORRECTLY
inflater.inflate(R.menu.menu_fragment_finder, menu);
//super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
return false;
default:
break;
}
return false;
}
}
menu_fragment_finder.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:title="#string/search_product"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always" />
</menu>

You are using the native action bar, not the appcompat-v7 backport, as evidenced by your inheriting from Activity and calling getActionBar(). Hence, remove the app namespace from your menu resource and change your app:showAsAction to android:showAsAction.

Related

Refresh Navigation Drawer Fragment Android?

I have a question about the navigation drawer fragment. As you know this navigation drawer has multiple sections. Let's say 3 sections (Home, Profile, Log out). My intent is when the user click on Log out, the navigation drawer will refresh itself to (Home, Log in).
I was trying to play with code but I couldn't figured it out..
The files that I have are:
MainActivity.java
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
android.support.v4.app.Fragment objFragment = null;
if(!GlobalVars.is_logged_in)
{
//if the user is NOT logged in
switch (position){
case 0:
objFragment = new Home();
break;
case 1:
objFragment = new LoginActivity();
break;
}
}
else
{
//if the user is logged in
switch (position){
case 0:
objFragment = new Home();
break;
case 1:
objFragment = new Profile();
break;
case 2:
objFragment = new Logout();
GlobalVars.is_logged_in = false;
mNavigationDrawerFragment.onCreateView(this.getLayoutInflater(), null, null);
break;
}
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, objFragment).commit();
}
public void onSectionAttached(int number) {
if(!GlobalVars.is_logged_in)
{
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section3);
break;
}
}
else
{
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = "Log out";
break;
}
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
/*if (id == R.id.action_settings) {
return true;
}*/
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_home, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
As you can notice the static variable is_logged_in which is a way to tell me if the user clicked on Log out or not.
I also updated the file NavigationDrawerFragment.java that Android studio created for me at the beginning step when it asked me to choose the type of activity and obviously I did not choose a blank one, I chose the Slide menu one that created this Navigation Drawer Fragment
So the code in NavigationDrawerFragment.java is
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
if(!GlobalVars.is_logged_in)
{
//the user is NOT logged in
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
//section1: home section2: profile section3:login
getString(R.string.title_section1),
getString(R.string.title_section3),
}));
}
else
{
//the user is logged in
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
//section1: home section2: profile section3:login
getString(R.string.title_section1),
getString(R.string.title_section2),
"Log out",
}));
}
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
/*if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}*/
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
//actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
Any help will be great from you guys...
What I would try is taking the code you use to set the adapter, and putting it into its own method like this:
private void setupListView(){
if(!GlobalVars.is_logged_in)
{
//the user is NOT logged in
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
//section1: home section2: profile section3:login
getString(R.string.title_section1),
getString(R.string.title_section3),
}));
}
else
{
//the user is logged in
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
//section1: home section2: profile section3:login
getString(R.string.title_section1),
getString(R.string.title_section2),
"Log out",
}));
}
}
Then, inside onCreateView(), replace all that code with the line setupListView(), and then also in the onClickListener for the listview you can check if they clicked logout/logon, and after you change the global variable you can call setupListView() again.
Alright, Thank you so much guys but I solved this issue by calling the part that is responsible for drawing the side menu bar in the MainAvtivity.java like the following
case 2:
objFragment = new Logout();
GlobalVars.is_logged_in = false;
mNavigationDrawerFragment.setupListView();
//mNavigationDrawerFragment.onCreateView(this.getLayoutInflater(), null, null);
break;
so each time the user click on the Log out it will execute the drawing function
Special thanks to #McAdam331
You can just call your item from navigationView object.
navigationView.getMenu().findItem(R.id.navigation_item_2).setTitle("Hello");

Android: Navigation-Drawer on all activities

I want to add navigation drawer on all actvities of my Android project. This is the code of the MainActivity:
public class MainActivity 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));
// App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawerLayout = (DrawerLayout) findViewById(R.drawable.ic_drawer_2);
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 */
);
// Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
// just styling option add shadow the right edge of the drawer
drawerLayout.setDrawerShadow(R.drawable.ic_drawer, GravityCompat.START);
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) {
displayView(position);
drawerLayout.closeDrawer(drawerListView);
}
private void displayView(int position)
{
switch (position)
{
case 0:
secondactivity();
break;
case 1:
Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(MainActivity.this, "3", Toast.LENGTH_LONG).show();
default:
break;
}
}
}
public void secondactivity (){
Intent cambioActivity;
cambioActivity = new Intent (this, SecondActivity.class);
startActivity(cambioActivity);
}
}
In this code I create the navigation drawer, I want the navigation drawer on all activities, so my Second Activity's code is this:
public class SecondActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondactivity);
}
The navigation drawer is on the first activity but there isn't on other activities, why? Can someone help me?
The easy way is that you should create fragments. If you are ready to for little hard thing then this is for you. It will let you have same navigation drawer in all activities.
Create drawer_n_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/drawer_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<YourDrawer
android:id="#+id/drawer_drawer"
android:layout_width="match_parent"
android:layout_height="fill_parent" >
</YourDrawer>
</RelativeLayout>
Your DrawerActivity.class
public class DrawerActivity extends Activity {
public RelativeLayout fullLayout;
public FrameLayout frameLayout;
#Override
public void setContentView(int layoutResID) {
fullLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.drawer_n_activity, null);
frameLayout = (FrameLayout) fullLayout.findViewById(R.id.drawer_frame);
getLayoutInflater().inflate(layoutResID, frameLayout, true);
super.setContentView(fullLayout);
//Your drawer content...
}
}
Now, to include same Navigation Drawer in all your activities and mind one more thing, all your activities must extend DrawerActivity
public class MainActivity extends DrawerActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //layout for 1st activity
}
}
public class SecondActivity extends DrawerActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity); //layout for 2nd activity
}
}
Okay Guys will share my way I do it (in case you are developing project after somebody and there is already tons of activities).
Finally I inflate navigation drawer with one line of code (in onCreate):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this; //context
//setContentView(R.layout.activity_favorites); // Was so
Utils.inflatedNavigationDrawerView(mContext, R.layout.activity_favorites); // Now is
//...
}
next what is Utils? :
public class Utils{
public static void inflatedNavigationDrawerView(Context context, int layoutId){
// Here get view of clear DrawerLayout
final View drawerLayout = View.inflate(context,R.layout.navigation_drawer_inflator, null);
// Next inflate to it passed layout for activity
final View mainLayout = View.inflate(context,layoutId, (ViewGroup) drawerLayout);
// And finally inflate to it fragment for NavigationDraver
final View fragmentLayout = View.inflate(context,R.layout.navigation_drawer_inflator_fragment, (ViewGroup) drawerLayout);
// Next we should try to get our drawer (should check with casting to each activity you want to insert to)
NavigationDrawerFragment drawerFragment = null;
// this block should be repeated for each activity you want to use in.
if (context instanceof FavoritesActivity){
// Set our pack of inflates to contentview
((FavoritesActivity) context).setContentView(mainLayout);
// And now we get NavigationDrawerFragment
drawerFragment = (NavigationDrawerFragment)
((FavoritesActivity) context).getSupportFragmentManager().findFragmentById(R.id.navigation_drawer_fragment);
}
if(drawerFragment != null){ // if null then we missed some castings for activity used in.
// Finally setup our drawer
drawerFragment.setUpEasy(R.id.navigation_drawer_fragment, (DrawerLayout)drawerLayout.findViewById(R.id.drawer_layout), (Toolbar) mainLayout.findViewById(R.id.app_bar));
}
}
}
If you would like to avoid creation of hamburger in Toolbar then you shoud in setUpEasy place: mDrawerToggle.setDrawerIndicatorEnabled(false);
Here is my sample of setup:
public void setUpEasy(int fragmentId, DrawerLayout drawerLayout, Toolbar toolBar) {
mContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolBar, R.string.open, R.string.close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if(!mUserLearnedDrawer){
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), Constants.PREFERENCES_LEARNDRAWER_KEY, mUserLearnedDrawer+"");
}
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerToggle.setDrawerIndicatorEnabled(false); // If false then no hamburger menu.
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
and views used:
// navigation_drawer_inflator.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dragAndDrop="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.widget.DrawerLayout>
// navigation_drawer_inflator_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation_drawer_fragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_marginTop="56dp"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
Finally if you will implement this - You will be able to insert navigation drawer to any activity on run. Cheers :)
Here's how I did it. Create the helper class. I also added some optional code for the ability to finish() the class.
public class NavDrawerHelper extends ContextWrapper{
public NavDrawerHelper(Context context){
super(context);
}
public void initNav(final DrawerLayout drawerLayout, NavigationView navigationView, Toolbar toolbar, final boolean isFinish){
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id){
case R.id.nav_home:
startActivity(new Intent(getBaseContext(), MainActivity.class));
if (isFinish) ((Activity)getBaseContext()).finish();
drawerLayout.closeDrawers();
break;
case R.id.nav_settings:
startActivity(new Intent(getBaseContext(), SettingsActivity.class));
if (isFinish) ((Activity)getBaseContext()).finish();
drawerLayout.closeDrawers();
break;
}
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(((Activity)getBaseContext()),drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
}
then add this code to all activities. This replaces your existing initNavigationDrawer() method.
public void initNavigationDrawer() {
//views
NavigationView navigationView = findViewById(R.id.navigation_view);
DrawerLayout drawerLayout = findViewById(R.id.drawer);
NavDrawerHelper navDrawerHelper = new NavDrawerHelper(this);
navDrawerHelper.initNav(drawerLayout, navigationView, toolbar, false);
}

How to start a new activity from item click in NavDrawer

I'm a novice. I was just wondering how to start a new (pre-defined) activity from clicking one of the option items inside a navigation drawer? I have just completed a tutorial on how to make the NavDrawer. Here is what I have so far in my main activity (it's called IntroActivity)
IntroActivity.java:
public class IntroActivity extends Activity {
private String[] drawerListViewItems;
private ListView drawerListView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
//Retrieve List items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.list_items);
//Retrieve ListView defined in intro_activity.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));
//App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* Host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* Image to replace "up" image*/
R.string.drawer_open, /* Open drawer description*/
R.string.drawer_close /* Close drawer description*/
);
//Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
//ADD SHADOW TO THE RIGHT EDGE OF DRAWER
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//Responding to clicks implementation:
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
//Sync the toggle state after onRestart... has occurred
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.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.intro, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Call ActionBarDrawerToggle.onOptionsItemSelected(),
//If it returns true, then it has handles 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) {
//I WOULD LIKE TO REPLACE THE FOLLOWING CODE WITH SOMETHING
//THAT CAN START A NEW ACTIVITY
/*Toast.makeText(IntroActivity.this, ((TextView)view).getText(),
Toast.LENGTH_LONG).show(); */
drawerLayout.closeDrawer(drawerListView);
}
}
}
Thanks if you can help.
Use this
Intent intent = new Intent(IntroActivity.this, YourNewActivity.class);
startActivity(intent);
where YourNewActivity is the activity you want to start

Android Navigation Drawer Level

I am having some problem with navigation drawer in Android. So these are the codes with me:
public class NavigationDrawer extends FragmentActivity {
private String[] drawerListViewItems;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private ActionBarDrawerToggle actionBarDrawerToggle;
protected DrawerLayout fullLayout;
protected FrameLayout actContent;
#Override
public void setContentView(final int layoutResID) {
fullLayout = (DrawerLayout) getLayoutInflater().inflate(
R.layout.navigation_drawer, null); // Your base layout here
actContent = (FrameLayout) fullLayout.findViewById(R.id.act_content);
getLayoutInflater().inflate(layoutResID, actContent, true);
super.setContentView(fullLayout);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,
drawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
drawerListView.bringToFront();
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position,
long id) {
switch (position) {
}
drawerLayout.closeDrawer(drawerListView);
}
}
}
And my xml file:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:divider="#CCCCCC"
android:dividerHeight="0.5dp"
android:paddingLeft="16dp"
android:paddingRight="16dp" />
<FrameLayout
android:id="#+id/act_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
And the string file where I declare the words for navigation drawer item:
<string-array name="items">
<item>Dashboard</item>
<item>Account</item>
<item>Setting</item>
<item>Recurring</item>
<item>Budget</item>
</string-array>
But with these code, the navigation drawer level is only one. What I am trying to do is there will be still sub item under Dashboard, Setting and Budget.
I wonder how to modify it so that the navigation drawer could take in one more level of items.
Thanks in advance.
EDIT
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
// private ListView mDrawerList;
private ExpandableListView mDrawerList;
private LinearLayout navDrawerView;
CustomExpandAdapter customAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mAnalyzeEventSelection;
private int selectedPosition;
List<SampleTO> listParent;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
navDrawerView = (LinearLayout) findViewById(R.id.navDrawerView);
mAnalyzeEventSelection = getResources().getStringArray(R.array.analyzeEvent_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.nav_left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
listParent = new ArrayList<SampleTO>();
listDataChild = new HashMap<String, List<String>>();
// Navigation Drawer of Flight starts
listParent.add(new SampleTO(getString(R.string.createEventDrawer), R.drawable.sun));
listParent.add(new SampleTO(getString(R.string.analyzeEventDrawer), R.drawable.solar_system));
listParent.add(new SampleTO(getString(R.string.qrCodeDrawer), R.drawable.moon));
listDataChild.put(getString(R.string.createEventDrawer), new ArrayList<String>());
listDataChild.put(getString(R.string.qrCodeDrawer), new ArrayList<String>());
listDataChild.put(getString(R.string.analyzeEventDrawer), Arrays.asList(mAnalyzeEventSelection));
customAdapter = new CustomExpandAdapter(this, listParent, listDataChild);
// setting list adapter
mDrawerList.setAdapter(customAdapter);
mDrawerList.setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);
// 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,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
/* if (savedInstanceState == null) {
selectItem(0);
}*/
}
#Override
protected void onResume() {
super.onResume();
mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForGroup(groupPosition));
parent.setItemChecked(index, true);
String parentTitle = ((SampleTO) customAdapter.getGroup(groupPosition)).getTitle();
if (parentTitle.equals(getString(R.string.createEventDrawer))){
Toast.makeText(
MainActivity.this,
"Create Event",
Toast.LENGTH_LONG).show();
setTitle(mAnalyzeEventSelection[selectedPosition]);
}
else if (parentTitle != getString(R.string.analyzeEventDrawer)) {
mDrawerLayout.closeDrawer(navDrawerView);
}
return false;
}
});
mDrawerList.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition));
parent.setItemChecked(index, true);
selectItem(childPosition);
return false;
}
});
}
#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(navDrawerView);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
private void selectItem(int position) {
selectedPosition = position;
mDrawerLayout.closeDrawer(navDrawerView);
switch(selectedPosition){
case 0:
Toast.makeText(
MainActivity.this,
"Event Pop",
Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(
MainActivity.this,
"Buffer",
Toast.LENGTH_LONG).show();
break;
}
setTitle(mAnalyzeEventSelection[selectedPosition]);
}
#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);
}
}
And my string file:
<resources>
<string name="app_name">Navigation Drawer Example</string>
<string name="createEventDrawer">Create Event</string>
<string name="analyzeEventDrawer">Analyze Event</string>
<string-array name="analyzeEvent_array">
<item>Past Event Population</item>
<item>Buffer</item>
</string-array>
<string name="qrCodeDrawer">QR Code Scan</string>
<string name="drawer_open">Open navigation drawer</string>
<string name="drawer_close">Close navigation drawer</string>
<string name="action_websearch">Web search</string>
<string name="app_not_available">Sorry, there\'s no web browser available</string>
<string name="_11">11</string>
Steps:
Change ListView to Expandablelistview.
Add subitems for the group items required.
Example :Custom Navigation Drawer

Main Class is never being called

I had my project in a project named "NavigationDrawer" and realised that considering this was an app that had more than a Nav Drawer in it that it should be changed and renamed to something relevant.
I tried to import the project but it kept saying that there were no source files found, so I started to do it the old fashioned way (copying and pasting everything over making sure that I changed package names etc). But now when I try to run the program its saying that it cant find the MainActivity method. It keeps saying "Class 'MainActivity' is never used" and without it, my program wont run obviously.
I'm at my wits end here guys haha, I know its likely that I haven't edited one of the files or something but if you could point me in the right direction that would be great.
My code:
package com.example.ColeraineTown;
imports....
public class MainActivity extends Activity {
private DrawerLayout DrawerLayout;
private ListView DrawerList;
private ActionBarDrawerToggle DrawerToggle;
private CharSequence DrawerTitle;
private CharSequence Title;
private String[] pageArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Title = DrawerTitle = getTitle();
pageArray = getResources().getStringArray(R.array.pageArray);
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
DrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
DrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
DrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, pageArray));
DrawerList.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
DrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
DrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace standard image in action bar */
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(Title);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(DrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
DrawerLayout.setDrawerListener(DrawerToggle);
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 = DrawerLayout.isDrawerOpen(DrawerList);
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 (DrawerToggle.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 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 PageFragment();
Bundle args = new Bundle();
args.putInt(PageFragment.ARG_PAGE_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
DrawerList.setItemChecked(position, true);
setTitle(pageArray[position]);
DrawerLayout.closeDrawer(DrawerList);
}
#Override
public void setTitle(CharSequence title) {
Title = title;
getActionBar().setTitle(Title);
}
/**
* 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.
DrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
DrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PageFragment extends Fragment {
public static final String ARG_PAGE_NUMBER = "page_number";
public PageFragment() {
// 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 pgNum = getArguments().getInt(ARG_PAGE_NUMBER);
String page = getResources().getStringArray(R.array.pageArray)[pgNum];
int imageId = getResources().getIdentifier(page.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(page);
return rootView;
}
}
}
You should declare it in the Android Manifest for that project.
<activity android:name="com.example.ColeraineTown.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
More docs

Categories

Resources