im trying to add a (+) icon on right of navigation bar in android, and then launch a new intent when clicked, but i can't seem to make it work, it's showing me the left icon to open/close the drawer, but the right icon is nowhere to be found.
Can anyone give me a hand on why its not working? im loosing my mind here...
The navigation bar looks like this, there's enough room for the right side
ActivityHome.java
package com.roneskinder.x111.activity.fragment;
import java.util.ArrayList;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
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.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.roneskinder.x111.PagerSlidingTabStrip;
import com.roneskinder.x111.R;
import com.roneskinder.x111.adapter.MenuAdapter;
import com.roneskinder.x111.config.AppConfig;
import com.roneskinder.x111.manager.ResourcesContentManager;
import com.roneskinder.x111.model.NavDrawerItem;
import com.roneskinder.x111.util.AppUtils;
public class ActivityHome extends ActionBarActivity {
private Context mContext;
DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] navMenuTitles;
private FragmentManager mFragmentManager;
private Fragment mFragment;
private ActionBarDrawerToggle mDrawerToggle;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> mNavDrawerItems;
private MenuAdapter menuAdapter;
private Dialog mCustomDialog;
private RelativeLayout mAdsView;
protected static String TAG = ActivityHome.class.toString();
protected static EditText nameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = ActivityHome.this;
showNavigationSlider();
if (savedInstanceState == null) {
selectItem(0);
}
// Init Ads
// initAds();
}
#Override
protected void onResume() {
super.onResume();
setTheme();
}
/**
* Method to show navigation drawer
*/
private void showNavigationSlider() {
if (mDrawerLayout == null) {
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(
R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(
R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mNavDrawerItems = new ArrayList<NavDrawerItem>();
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[0],
navMenuIcons.getResourceId(0, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[1],
navMenuIcons.getResourceId(1, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[2],
navMenuIcons.getResourceId(2, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[3],
navMenuIcons.getResourceId(3, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[4],
navMenuIcons.getResourceId(4, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[5],
navMenuIcons.getResourceId(5, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[6],
navMenuIcons.getResourceId(6, -1)));
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
menuAdapter = new MenuAdapter(ActivityHome.this);
menuAdapter.setList(mNavDrawerItems);
mDrawerList.setAdapter(menuAdapter);
mDrawerToggle = new ActionBarDrawerToggle
(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.app_name, /* "open drawer" description for accessibility */
R.string.app_name /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
}
#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);
mDrawerToggle.syncState();
setTheme();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Here im inflating my menu options
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.new_list, 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);
// here im setting its visibility to true/false depending on the drawer position
menu.findItem(R.id.action_new_list).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
break;
}
// here im adding a click event in the button
case R.id.action_new_list:
aboutClicked();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
onItemClickListerner(position);
}
}
/**
* Display selected navigation drawer list item
* */
private void onItemClickListerner(int position) {
Intent intent = null;
switch (position) {
case 0:
//intent = new Intent(mContext, ActivitySettings.class);
//startActivity(intent);
mDrawerLayout.closeDrawers();
break;
case 1:
//intent = new Intent(mContext, ActivityTheme.class);
//startActivity(intent);
mDrawerLayout.closeDrawers();
break;
case 2:
//updateClicked();
mDrawerLayout.closeDrawers();
break;
case 3:
//moreAppClicked();
mDrawerLayout.closeDrawers();
break;
case 4:
//shareClicked(getString(R.string.share_subject),TabsApplication.getAppUrl());
mDrawerLayout.closeDrawers();
break;
case 5:
//rateAppClicked();
mDrawerLayout.closeDrawers();
break;
case 6:
newListClicked();
mDrawerLayout.closeDrawers();
break;
}
}
/**
* Method to check for updated app.
*/
private void updateClicked() {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="
+ mContext.getPackageName())));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ mContext.getPackageName())));
}
}
/**
* Method to rate the app.
*/
private void rateAppClicked() {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="
+ mContext.getPackageName())));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ mContext.getPackageName())));
}
}
/**
* Method to share app via different available share apps
*/
private void shareClicked(String subject, String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(intent,
getString(R.string.share_via)));
}
/**
* Method to Show more apps from Developer
*/
private void moreAppClicked() {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(String
.format("market://search?q=pub:%s",
AppConfig.PLAYSTORE_ACCOUNT_NAME))));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse(String
.format("https://play.google.com/store/apps/developer?id=%s&hl=en",
AppConfig.PLAYSTORE_ACCOUNT_NAME))));
}
}
/**
* Method to show about
*/
private void aboutClicked() {
try {
String appname = null;
appname = getString(R.string.app_name_message) + " "
+ getString(R.string.app_name) + "" + "\n\n";
String appversion = getString(R.string.app_version)
+ " "
+ mContext.getPackageManager().getPackageInfo(
mContext.getPackageName(),
PackageInfo.CONTENTS_FILE_DESCRIPTOR).versionCode
+ "\n\n";
String name = getString(R.string.response_message);
showAboutCustomDialog(getString(R.string.about), appname
+ appversion + name, getString(R.string.ok),
getString(R.string.cancel), true);
} catch (NameNotFoundException ex) {
ex.printStackTrace();
}
}
/**
* Method to show custom dialog.
*
* #param title
* #param message
* #param okText
* #param cancelText
* #param singleButtonEnabled
*/
private void showAboutCustomDialog(String title, String message,
String okText, String cancelText, boolean singleButtonEnabled) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.about_dialog_view, null);
RelativeLayout titlebarView = (RelativeLayout) dialogView
.findViewById(R.id.title_bar_view);
titlebarView.setBackgroundColor(ResourcesContentManager.getInstance()
.getTitleBarColor(mContext, -1));
Button okButton = (Button) dialogView.findViewById(R.id.ok_button);
Button cancelButton = (Button) dialogView
.findViewById(R.id.cancel_button);
okButton.setBackgroundResource(ResourcesContentManager.getInstance()
.getButtonBackgroundResource(mContext, -1));
okButton.setTextAppearance(mContext, ResourcesContentManager
.getInstance().getButtonTextStyle(mContext, -1));
cancelButton.setBackgroundResource(ResourcesContentManager
.getInstance().getButtonBackgroundResource(mContext, -1));
cancelButton.setTextAppearance(mContext, ResourcesContentManager
.getInstance().getButtonTextStyle(mContext, -1));
TextView titleTextview = (TextView) dialogView
.findViewById(R.id.title_textview);
TextView messageTextview = (TextView) dialogView
.findViewById(R.id.message_textview);
TextView name = (TextView) dialogView.findViewById(R.id.email_textview);
name.setText("test#test.com");
if (mCustomDialog != null) {
mCustomDialog.dismiss();
mCustomDialog = null;
}
mCustomDialog = new Dialog(mContext,
android.R.style.Theme_Translucent_NoTitleBar);
mCustomDialog.setContentView(dialogView);
mCustomDialog.setOnKeyListener(new OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == keyCode) {
dialog.dismiss();
}
return false;
}
});
mCustomDialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
}
});
mCustomDialog.setCanceledOnTouchOutside(false);
titleTextview.setText(title);
messageTextview.setText(message);
if (singleButtonEnabled) {
okButton.setText(okText);
cancelButton.setVisibility(View.GONE);
} else {
okButton.setText(okText);
cancelButton.setText(cancelText);
}
/**
* Listener for OK button click.
*/
okButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCustomDialog.dismiss();
}
});
/**
* Listener for Cancel button click.
*/
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCustomDialog.dismiss();
}
});
mCustomDialog.show();
}
/**
* Method to create new list
*/
private void newListClicked() {
showCreateListDialog("Nueva lista de compras", "Crear", getString(R.string.cancel), false);
}
/**
* Method to create new list dialog
*
* #param title
* #param message
* #param okText
* #param cancelText
* #param singleButtonEnabled
*/
private void showCreateListDialog(String title,
String okText, String cancelText, boolean singleButtonEnabled) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.new_list_dialog_view, null);
RelativeLayout titlebarView = (RelativeLayout) dialogView
.findViewById(R.id.title_bar_view);
titlebarView.setBackgroundColor(ResourcesContentManager.getInstance()
.getTitleBarColor(mContext, -1));
Button okButton = (Button) dialogView.findViewById(R.id.ok_button);
Button cancelButton = (Button) dialogView.findViewById(R.id.cancel_button);
okButton.setBackgroundResource(ResourcesContentManager.getInstance().getButtonBackgroundResource(mContext, -1));
okButton.setTextAppearance(mContext, ResourcesContentManager.getInstance().getButtonTextStyle(mContext, -1));
cancelButton.setBackgroundResource(ResourcesContentManager.getInstance().getButtonBackgroundResource(mContext, -1));
cancelButton.setTextAppearance(mContext, ResourcesContentManager.getInstance().getButtonTextStyle(mContext, -1));
TextView titleTextview = (TextView) dialogView.findViewById(R.id.title_textview);
nameList = (EditText) dialogView.findViewById(R.id.list_name);
if (mCustomDialog != null) {
mCustomDialog.dismiss();
mCustomDialog = null;
}
mCustomDialog = new Dialog(mContext,android.R.style.Theme_Translucent_NoTitleBar);
mCustomDialog.setContentView(dialogView);
mCustomDialog.setOnKeyListener(new OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == keyCode) {
dialog.dismiss();
}
return false;
}
});
mCustomDialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
}
});
mCustomDialog.setCanceledOnTouchOutside(false);
titleTextview.setText(title);
if (singleButtonEnabled) {
okButton.setText(okText);
cancelButton.setVisibility(View.GONE);
} else {
okButton.setText(okText);
cancelButton.setText(cancelText);
}
/**
* Listener for OK button click.
*/
okButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// if list has valid name, save
String name = nameList.getText().toString();
if(!name.matches("")){
Intent intent = new Intent(mContext, ActivityAddProductsToList.class);
startActivity(intent);
mCustomDialog.dismiss();
}else{
AppUtils.showToast(mContext, "Por favor ingrese el nombre de la nueva lista");
}
}
});
/**
* Listener for Cancel button click.
*/
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCustomDialog.dismiss();
}
});
mCustomDialog.show();
}
private void selectItem(int position) {
switch (position) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content,
FragmentPageSlidingTabStrip.newInstance(),
FragmentPageSlidingTabStrip.TAG).commit();
break;
default:
// mFragment = new PlanetFragment();
// Bundle args = new Bundle();
// args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
// mFragment.setArguments(args);
//
// getSupportFragmentManager().beginTransaction()
// .add(R.id.content, mFragment).commit();
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onDestroy() {
if (mContext != null) {
if (mCustomDialog != null) {
mCustomDialog.dismiss();
mCustomDialog = null;
}
mDrawerList = null;
mDrawerTitle = null;
mTitle = null;
navMenuTitles = null;
mFragmentManager = null;
mFragment = null;
mDrawerLayout = null;
mDrawerToggle = null;
mContext = null;
super.onDestroy();
}
}
/**
* Method to set themes backgrounds
*/
private void setTheme() {
int actionBarTitleId = Resources.getSystem().getIdentifier(
"action_bar_title", "id", "android");
if (actionBarTitleId > 0) {
TextView title = (TextView) findViewById(actionBarTitleId);
title.setTextAppearance(mContext, R.style.ActionBarTitleTextStyle);
}
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(ResourcesContentManager.getInstance()
.getTitleBarColor(mContext, -1)));
mDrawerList.setBackgroundColor(ResourcesContentManager.getInstance()
.getScreenBgColor(mContext, -1));
PagerSlidingTabStrip tabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabStrip.setIndicatorColor(ResourcesContentManager.getInstance()
.getTitleBarColor(mContext, -1));
}
/**
* Method to inits the ads banner view
*/
/*
private void initAds() {
if (mAdsView == null) {
mAdsView = (RelativeLayout) findViewById(R.id.bottom_ads_view);
}
if (AppConfig.BANNER_ADS_ENABLED) {
mAdsView.setVisibility(View.VISIBLE);
AppUtils.addAdsBannerView(ActivityHome.this, mAdsView);
} else {
mAdsView.setVisibility(View.GONE);
}
}
*/
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="#+id/content_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="#+id/bottom_ads_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/bottom_ads_view" >
</RelativeLayout>
</RelativeLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="#dimen/slider_width"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:background="#color/slider_bg_color"
android:choiceMode="singleChoice"
android:divider="#color/slider_divider_color"
android:dividerHeight="1dp" />
</android.support.v4.widget.DrawerLayout>
new_list.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/action_new_list"
android:icon="#drawable/action_search"
android:title="#string/action_new_list"
android:showAsAction="ifRoom|withText" />
</menu>
Change following line in onCreateOptionsMenu
return super.onCreateOptionsMenu(menu);
to
return true;
The id of your menu item is the same name as the string (action_new_list). I'd try changing that to see if there's a collision.
2. Add a titleCondensed attribute, as that's all that will show in your Options Menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/action_new_list"
android:icon="#drawable/action_search"
android:title="#string/action_new_list"
android:titleCondensed="#string/new_string"
android:showAsAction="ifRoom|withText" />
</menu>
Related
I have succesfully implemented the navigation drawer in my MainMenu.class activity. In my navigation drawer, I have the following rows (Home, About, All reminders, Text reminders, Photo reminders, and etc). I am able to switch to their different respective activities from rows 2 onwards (e.g. from About onwards). The problem is, no matter what i do, I am unable to make the Home proceed to my intended Activity (e.g. I want to go to the MainActivity.class activity upon clicking on Home).
Here are my codes for MainMenu.class:
package sg.edu.nus.is3261proj;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Toast;
import com.beardedhen.androidbootstrap.TypefaceProvider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Handler;
public class MainMenu extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks{
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
/**
* 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_menu);
TypefaceProvider.registerDefaultIconSets();
db = new MyDB(this);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
String textContain = listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition);
if(textContain.contains("Date")) {
Intent i = new Intent(getBaseContext(), TextReminderDetails.class);
i.putExtra("title", listDataHeader.get(groupPosition));
i.putExtra("details", listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition));
startActivity(i);
}
else {
Intent i = new Intent(getBaseContext(), PhotoReminderDetails.class);
i.putExtra("title", listDataHeader.get(groupPosition));
i.putExtra("details", listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition));
startActivity(i);
}
return false;
}
});
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));
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
ArrayList<String[]> records = getAllRecords();
for (int i = 0; i < records.size(); i++) {
String[] record = records.get(i);
String title = record[1];
listDataHeader.add(title);
List<String> details = new ArrayList<String>();
details.add(record[2] + "\n" + record[3]);
listDataChild.put(title,details); // Header, Child data
}
ArrayList<String[]> photoRecords = getAllPhotoRecords();
for (int i = 0; i < photoRecords.size(); i++) {
String[] record = photoRecords.get(i);
String title = record[1];
listDataHeader.add(title);
List<String> details = new ArrayList<String>();
details.add(record[3]);
listDataChild.put(title,details); // Header, Child data
}
}
public void onClick_addNewReminder(View view){
Intent intent = new Intent(this, NewReminder.class);
this.startActivity(intent);
}
MyDB db;
public ArrayList<String[]> getAllRecords(){
db.open();
Cursor c = db.getAllRecords();
ArrayList<String[]> records = new ArrayList<String[]>();
if(c.moveToFirst()){
do {
String[] record = {
c.getString(0), c.getString(1), c.getString(2), c.getString(3)};
records.add(record);
} while (c.moveToNext());
}
db.close();
return records;
}
public ArrayList<String[]> getAllPhotoRecords(){
db.open();
Cursor c = db.getAllPhotoRecords();
ArrayList<String[]> photoRecords = new ArrayList<String[]>();
if(c.moveToFirst()){
do {
String[] photoRecord = {
c.getString(0), c.getString(1), c.getString(2), c.getString(3)};
photoRecords.add(photoRecord);
} while (c.moveToNext());
}
db.close();
return photoRecords;
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
Intent intent;
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
intent = new Intent(this, AboutActivity.class);
startActivity(intent);
break;
case 3:
mTitle = getString(R.string.title_section3);
intent = new Intent(this, MainMenu.class);
startActivity(intent);
break;
case 4:
mTitle = getString(R.string.title_section4);
intent = new Intent(this, TextReminderMenu.class);
startActivity(intent);
break;
case 5:
mTitle = getString(R.string.title_section5);
intent = new Intent(this, PhotoReminderMenu.class);
startActivity(intent);
break;
case 6:
mTitle = getString(R.string.title_section6);
break;
case 7:
mTitle = getString(R.string.title_section7);
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.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainMenu) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
and NavigationDrawerFragment.class:
package sg.edu.nus.is3261proj;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
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;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
getString(R.string.title_section5),
getString(R.string.title_section6),
getString(R.string.title_section7),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).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;
}
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 ((AppCompatActivity) 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);
}
}
On click of home button write below code so you can go to main activity.
Intent main= new Intent(mContext, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
My code does a different kinds of things, but nothing exactly like what I want.
Problem -
When the app starts, the home doesn´t show.
When an item is selected, the lateral bar (NavigationDrawer) is not hidden. It is not showing the next fragment until I click outside the lateral bar.
Please help :(
import java.util.ArrayList;
import org.json.JSONException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("NewApi")
public class MainActivity extends Activity {
//paypal
public static final String TAG = "Inscripción Evento";
public static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
public static final String CONFIG_CLIENT_ID = "AU3fdxNPtXe8cz2lbvcBYt7jvJ12uA9CeYpQBNZgfHy5CvxCS6SDDGHIp7nqbBMNksrQh9u0zL3zXRnM";
public static final int REQUEST_CODE_PAYMENT = 1;
public static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
public static final int REQUEST_CODE_PROFILE_SHARING = 3;
public static PayPalConfiguration config = new PayPalConfiguration().environment(CONFIG_ENVIRONMENT).clientId(CONFIG_CLIENT_ID).languageOrLocale("es_MX").merchantName("iESNAJ").merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy")).merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
//fin paypal
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
TextView BarTitulo;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
static String URL = "";
iGuepardosVariables variables = new iGuepardosVariables();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setCustomView(R.layout.iguepardos_action_bar);
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setIcon(R.drawable.space);
//getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.header));
getActionBar().setDisplayHomeAsUpEnabled(true);//agregado
((ActionBar) getActionBar()).setHomeButtonEnabled(true);
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
try
{
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.list_item_title));
yourTextView.setTextSize(13);
yourTextView.setGravity(Gravity.CENTER_HORIZONTAL);//agregado
yourTextView.setVisibility(View.INVISIBLE);
}
catch (Exception e) {}
CreaMenu();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.menu01, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
//getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
if (savedInstanceState == null) {
if (navDrawerItems.get(0).getTitle() != null & navDrawerItems.get(1).getTitle() != null) {
}
else if (navDrawerItems.get(0).getTitle() != null) {
} else {
}
}
}
}
private void CreaMenu()
{
this.VerificaPerfilLocal();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
//Declaramos el header el caul sera el layout de header.xml
//View header = getLayoutInflater().inflate(R.layout.header, null);
//Establecemos header
//mDrawerList.addHeaderView(header);
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
//Perfil
if(variables.usuario.equals("")){
navDrawerItems.add(new NavDrawerItem(R.id.icon, "Usuario", "No ha iniciado sesión", null, null, 0, false));
}
else
{
navDrawerItems.add(new NavDrawerItem(R.id.icon, "Usuario", variables.usuario, null, null, 0, false));
}
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Calendario de Eventos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -2)));
// Resultados
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Contacto
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Registra tu Evento
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// Onclick MX
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// Iniciar sesión
if(variables.usuario.equals(""))
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
else
navDrawerItems.add(new NavDrawerItem("Cerrar Sesión", navMenuIcons.getResourceId(6, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener((OnItemClickListener) new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final int thePos = position;
mDrawerLayout.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView) {
boolean wasChecked = !mDrawerList.isItemChecked(thePos);
//Toast.makeText(homeActivity, "Item pulsado: " + wasChecked, Toast.LENGTH_SHORT).show();
mDrawerList.setItemChecked(thePos, !wasChecked);
Fragment fragment = null;
switch (thePos) {
/*case 0:
fragment = new HomeFragment();
break;*/
case 1:
fragment = new HomeFragment();
break;
case 2:
fragment = new CalendarioFragment();
break;
case 5:
fragment = new ContactoFragment();
break;
case 6:
fragment = new OnclickFragment();
break;
default:
break;
}
if (fragment != null) {
try{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(thePos, true);
mDrawerList.setSelection(thePos);
setTitle(navMenuTitles[thePos]);
mDrawerLayout.closeDrawer(mDrawerList);
}
catch(Exception E)
{
Log.e("MainActivity", "Error in creating fragment");
}
}
else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
CreaMenu();
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
#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);
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
/**
* TODO: Send the authorization response to your server, where it can
* exchange the authorization code for OAuth access and refresh tokens.
*
* Your server must then store these tokens, so that your server code
* can execute payments for this user in the future.
*
* A more complete example that includes the required app-server to
* PayPal-server integration is available from
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MainActivity.REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(MainActivity.TAG, confirm.toJSONObject().toString(4));
Log.i(MainActivity.TAG, confirm.getPayment().toJSONObject().toString(4));
/**
* TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
* or consent completion.
* See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
* for more details.
*
* For sample mobile backend interactions, see
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
Fragment f = MainActivity.this.getFragmentManager().findFragmentById(R.id.frame_container);
if (f instanceof EventoFragment)
EventoFragment.SendEmailConfirmation(variables.direccionIpWS);
Toast.makeText(getApplicationContext(), "Se ha enviado un e-mail con la confirmación de la inscripción.", Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), "PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e(MainActivity.TAG, "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i(MainActivity.TAG, "The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(MainActivity.TAG,"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
}
}
#Override
public void onDestroy() {
// Stop service when done
MainActivity.this.stopService(new Intent(MainActivity.this, PayPalService.class));
super.onDestroy();
}
private void VerificaPerfilLocal()
{
try
{
SharedPreferences preferencias;
preferencias = getSharedPreferences("loginGuepardos", Context.MODE_PRIVATE);
if(variables.usuario.toString().equals("") && preferencias.contains("ID_EMAIL"))
{
variables.usuario = preferencias.getString("ID_EMAIL", null);
}
}
catch(Exception e) {}
}
}
If you have an idea on what is wrong, please help me fix the behavior.
For starters, try this, it should hide the lateral bar when you click on an item:
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.menu01, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
//getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
I'll look more deeply into your problem now.
I'm trying to create a favorite list in my app, for this target I used this tutorial:
http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/
but to get favorites I used NavigationDrawer instead ActionBar.
The problem is that nothing happens when I choose Favorites or Home in Drawer.
The Logcat shows only one error which not connected with my problem.
Where did I mistake?
Error:
06-30 17:41:48.530 6971-6971/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.boom.kayakapp, PID: 6971
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.widget.ImageView.getTag()' on a null object reference
at com.boom.kayakapp.activities.MainActivity$2.onItemLongClick(MainActivity.java:148)
at android.widget.AbsListView.showContextMenuForChild(AbsListView.java:3162)
at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:693)
at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:693)
at android.view.View.showContextMenu(View.java:4853)
at android.view.View.performLongClick(View.java:4822)
at android.widget.TextView.performLongClick(TextView.java:8684)
at android.view.View$CheckForLongPress.run(View.java:19840)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
--------- beginning of system
06-30 17:41:48.572 933-933/? E/EGL_emulation﹕ tid 933: eglCreateSyncKHR(1237): error 0x3004 (EGL_BAD_ATTRIBUTE)
06-30 17:41:50.823 1232-1274/system_process E/InputDispatcher﹕ channel '10153f49 com.boom.kayakapp/com.boom.kayakapp.activities.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-30 17:42:02.006 7546-7546/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
06-30 17:42:02.006 7546-7546/? E/android.os.Debug﹕ failed to load memtrack module: -2
06-30 17:42:02.041 7546-7555/? E/art﹕ Thread attaching while runtime is shutting down: Binder_1
06-30 17:42:02.402 7560-7560/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
06-30 17:42:02.402 7560-7560/? E/android.os.Debug﹕ failed to load memtrack module: -2
06-30 17:42:02.460 7560-7570/? E/art﹕ Thread attaching while runtime is shutting down: Binder_1
Main Activity:
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.adapters.NavDrawerListAdapter;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.fragment.AirlinesFragment;
import com.boom.kayakapp.fragment.FavoriteFragment;
import com.boom.kayakapp.fragment.HomeFragment;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.model.NavDrawerItem;
import com.boom.kayakapp.util.SharedPreference;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private Fragment contentFragment;
AirlinesFragment airlinesFragment;
FavoriteFragment favoriteFragment;
// JSON Node names
public static final String TAG_NAME = "name";
public static final String TAG_PHONE = "phone";
public static final String TAG_SITE = "site";
public static final String TAG_LOGO = "logoURL";
public static final String TAG_CODE = "code";
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Airlines json url
private static final String url = "https://www.kayak.com/h/mobileapis/directory/airlines";
public ProgressDialog pDialog;
public List<Airlines> airlinesList = new ArrayList<Airlines>();
public ListView listView;
public AirlinesAdapter adapterAirlines;
SharedPreference sharedPreference;
// DrawerLayout
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapterDrawer;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
// SharedPrefs
sharedPreference = new SharedPreference();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Json Array
listView = (ListView) findViewById(R.id.list);
adapterAirlines = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapterAirlines);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview OnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(MainActivity.this, airlinesList.get(position));
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(MainActivity.this, airlinesList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
// changing action bar color
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest airlinesReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Airlines airlines = new Airlines();
airlines.setName(obj.getString("name"));
airlines.setLogoURL(obj.getString("logoURL"));
airlines.setPhone(obj.getString("phone"));
airlines.setCode(obj.getInt("code"));
airlines.setSite(obj.getString("site"));
// adding airlines to array
airlinesList.add(airlines);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapterAirlines about data changes
// so that it renders the list view with updated data
adapterAirlines.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(airlinesReq);
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* This is called when orientation is changed.
*/
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavoriteFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID) != null) {
setFragmentTitle(R.string.favorites);
contentFragment = fragmentManager
.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID);
}
}
}
if (fragmentManager.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID) != null) {
airlinesFragment = (AirlinesFragment) fragmentManager
.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID);
contentFragment = airlinesFragment;
}
} else {
airlinesFragment = new AirlinesFragment();
switchContent(airlinesFragment, AirlinesFragment.ARG_ITEM_ID);
}
/*
From this place DrawerLayout starts
*/
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Favorites
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Recycle the typed array
navMenuIcons.recycle();
// setting the nav drawer list adapterDrawer
adapterDrawer = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapterDrawer);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
){
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
// if (mDrawerToggle.onOptionsItemSelected(item)) {
// return true;
// }
// Handle action bar actions click
// switch (item.getItemId()) {
// case R.id.action_settings:
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
//
switch (item.getItemId()) {
case R.id.action_settings:
setFragmentTitle(R.string.favorites);
favoriteFragment = new FavoriteFragment();
switchContent(favoriteFragment, FavoriteFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FavoriteFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#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);
}
#Override
public void onDestroy () {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
if (contentFragment instanceof FavoriteFragment) {
outState.putString("content", FavoriteFragment.ARG_ITEM_ID);
} else {
outState.putString("content", AirlinesFragment.ARG_ITEM_ID);
}
super.onSaveInstanceState(outState);
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate()) ;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
//Only FavoriteFragment is added to the back stack.
if (!(fragment instanceof AirlinesFragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
protected void setFragmentTitle(int resourseId) {
setTitle(resourseId);
getSupportActionBar().setTitle(resourseId);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof ProductListFragment or if the stack entry count is == 0, then
* we finish the activity.
* In other words, from AirlinesFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
super.onBackPressed();
} else if (contentFragment instanceof AirlinesFragment
|| fm.getBackStackEntryCount() == 0) {
finish();
}
}
#Override
public void onResume() {
super.onResume();
}
}
FavoriteFragment:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;
import java.util.List;
public class FavoriteFragment extends Fragment {
public static final String ARG_ITEM_ID = "favorite_list";
ListView favoriteList;
SharedPreference sharedPreference;
List<Airlines> favorites;
Activity activity;
AirlinesAdapter airlinesAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_list, container,
false);
// Get favorite items from SharedPreferences.
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(activity);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
favoriteList = (ListView) view.findViewById(R.id.list);
if (favorites != null) {
airlinesAdapter = new AirlinesAdapter(activity, favorites);
favoriteList.setAdapter(airlinesAdapter);
favoriteList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long arg3) {
}
});
favoriteList
.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(
AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view
.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity,
favorites.get(position));
Toast.makeText(
activity,
activity.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(activity,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
airlinesAdapter.remove(favorites
.get(position));
Toast.makeText(
activity,
activity.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
return view;
}
public void showAlert(String title, String message) {
if (activity != null && !activity.isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(activity)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void onResume() {
getActivity().setTitle(R.string.favorites);
super.onResume();
}
}
The error looks pretty self-explaining to me.
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.Object android.widget.ImageView.getTag()' on a null object
reference
The button you are trying to find by id after a long click is returning null so you are unable to use the getTag() method on that object.
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
So you should check if the favorite list is really containing a view (button) with that ID. Try using getActivity().findViewByID() instead to test this.
navigation drawer list class
package com.example.navigation;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
this is my main activity
package com.example.navigation;
import java.util.ArrayList;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
protected RelativeLayout _completeLayout, _activityLayout;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// if (savedInstanceState == null) {
// // on first time display view for first nav item
// // displayView(0);
// }
}
public void set(String[] navMenuTitles, TypedArray navMenuIcons) {
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items
if (navMenuIcons == null) {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i]));
}
} else {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i],
navMenuIcons.getResourceId(i, -1)));
}
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// getSupportActionBar().setIcon(R.drawable.ic_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_launcher, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
// menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
switch (position) {
case 0:
Intent intent = new Intent(this, FirstActivity.class);
startActivity(intent);
finish();// finishes the current activity
break;
case 1:
Intent intent1 = new Intent(this, SecondActivity.class);
startActivity(intent1);
finish();// finishes the current activity
break;
// case 2:
// Intent intent2 = new Intent(this, third.class);
// startActivity(intent2);
// finish();
// break;
// case 3:
// Intent intent3 = new Intent(this, fourth.class);
// startActivity(intent3);
// finish();
// break;
// case 4:
// Intent intent4 = new Intent(this, fifth.class);
// startActivity(intent4);
// finish();
// break;
// case 5:
// Intent intent5 = new Intent(this, sixth.class);
// startActivity(intent5);
// finish();
// break;
default:
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(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);
}
}
drawer item
package com.example.navigation;
public class NavDrawerItem {
private String title;
private int icon;
public NavDrawerItem() {
}
public NavDrawerItem(String title, int icon) {
this.title = title;
this.icon = icon;
}
public NavDrawerItem(String title) {
this.title = title;
}
public String getTitle() {
return this.title;
}
public int getIcon() {
return this.icon;
}
public void setTitle(String title) {
this.title = title;
}
public void setIcon(int icon) {
this.icon = icon;
}
}
I created a navigation drawer menu item but now i want to create sub menu item in navigation drawer menu item. So how can i create this please suggest me thanks in advance
Here is my navigation Drawer menu item code which we r created in String.xml
<string-array name="nav_drawer_items">
<item>First</item>
<item>Second</item>
<item>Third</item>
<item>Fourth</item>
<item>Fifth</item>
<item>Sixth</item>
</string-array>
Check the following link..
that helps you to create expandable listview in navigation drawer.
android-custom-navigation-drawer
You should check Andtroid Hive Example also.
Some more links that may be helpful to you.
Navigation drawer with Expandable list view - 1
Navigation drawer with Expandable list view - 2
You need customize your navigation drawer menu. Actually looks like use a simple ListView, if you need subsecction, you should use ExpandableListView. Something like this:
http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/
If show your code or how you create the navigation drawer, we can help you with replace your actual menu with the custom menu.
I currently have a menu that I load into my Toolbar which looks like this:
<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:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
android:onClick="goToSearch"
android:title="Search"/>
<item android:id="#+id/action_barcode"
android:icon="#drawable/bar"
android:title="barcode"
app:showAsAction="ifRoom"
android:onClick="scanBarcode"/>
</menu>
When you click the barcode icon, it loads my barcode scanning fragment. I want to clean up my toolBar and not have multiple icons up there. Essentially I want my search icon, that opens up when clicked to have two functions.
When clicked open the search bar.
When long pressed, open my barcode scan fragment.
Currently Number one works, looking at how to employ number 2.
This is what my code looks liek for launching the barcode scan fragment and search.
import android.IntentIntegrator;
import android.IntentResult;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
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.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
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.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Created by Mike and Simon on 2/22/14.
*/
public class MainDrawer2 extends ActionBarActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//Crashlytics.start(this);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
// Set a toolbar to replace the action bar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getActionBar().setDisplayHomeAsUpEnabled(true);
//enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_menu_white, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
//getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
//getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
//getActionBar().setHomeButtonEnabled(true);
}
}
public void setActionBarTitle(String title) {
//getActionBar().setTitle(title);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
//getActionBar().setTitle(mTitle);
}
#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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (mCurrentNavItem == null){
}
else{
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
//if(navItem == mCurrentNavItem){
// return;
//}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
//setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
//mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
//mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
//test to keep item not selected
int toClear=mDrawerList.getCheckedItemPosition();
if (toClear >= 0) {
mDrawerList.setItemChecked(toClear, false);
}
mDrawerLayout.closeDrawer(mDrawerList);
//setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
public void scanBarcode(MenuItem item){
//open scanner
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
//todo: set scan content into setting, load new fragment which calls async task below. New
//todo: fragment will have same ui as search. :-)
Fragment Fragment_one;
FragmentManager man= this.getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
BarcodeFrag fragmentNew = new BarcodeFrag();
Bundle bundle = new Bundle();
bundle.putString("scanContent", scanContent);
fragmentNew.setArguments(bundle);
tran.replace(R.id.main, fragmentNew);//tran.
tran.addToBackStack(null);
//tran.commit();
tran.commitAllowingStateLoss();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
The action bar concept doesn't count on this requirement, so using built-in functionality you'll never be able to achieve what you need.
You can, however, introduce your own custom layout in stock action bar and do whatever you want there. See an example here:
http://javatechig.com/android/actionbar-with-custom-view-example-in-android