I have a navigation drawer that when an Item is selected, it loads the new fragment but never closes the drawer. My navigation drawer code looks like this:
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);
toolbar.setTitleTextColor(0xFFFFFFFF);
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();
}
}
}
I also have an enum that I use for my drawer which looks like this:
import android.support.v4.app.Fragment;
public enum MainNavItem
{
// Displayed in NavDrawerListAdapter
STATISTICS("Your Statistics", R.layout.statistics_pagelayout, StatisticsPage.class),
DISCOVER ("Discover", R.layout.activity_discover, BPTopBeers.class),
PORTFOLIO ("Portfolio", R.layout.activity_portfolio, Portfolio.class),
DRINKLOCAL ("Drink Local", R.layout.beer_location_list, DrinkLocal.class),
Map ("Brewery Map", R.layout.activity_brewmap, MapTabs.class),
LISTS ("Your Lists", R.layout.activity_search, AllLists.class),
NEWS ("News", R.layout.activity_news, NewsWeb.class),
Find ("Nearby Breweries", R.layout.beer_location_list, FindBrewery.class),
CONTACT ("Contact", R.layout.activity_contact, ContactPage.class),
// Items NOT displayed in NavDrawerListAdapter
SEARCH ("Search", R.layout.activity_search, Search.class),
;
private static MainNavItem LAST_NAV_ITEM = CONTACT;
private String mTitleResId;
private int mLayoutResId;
private Class<? extends Fragment> mFragClass;
private MainNavItem(String titleResId, int layoutResId, Class<? extends Fragment> fragClass)
{
mTitleResId = titleResId;
mLayoutResId = layoutResId;
mFragClass = fragClass;
}
public int getLayoutResId()
{
return mLayoutResId;
}
public String getTitleResId()
{
return mTitleResId;
}
public Class<? extends Fragment> getFragClass()
{
return mFragClass;
}
public static MainNavItem[] getNavAdapterItems()
{
int count = LAST_NAV_ITEM.ordinal() + 1;
MainNavItem[] adapterItems = new MainNavItem[count];
for(int i = 0; i < count; i++){
adapterItems[i] = values()[i];
}
return adapterItems;
}
}
Add this to your onItemClick method of the mDrawerList
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
I can't find where are you loading fragment in your code but you are probably missing mDrawerToggle.onDrawerClosed(mDrawerLayout); before you replace your fragments.
Related
I've successfully build this app but the app keep on crashing in my emulator/phone. It seen like it can't read my MainActivity
MainActivity.java
package com.example.remotelab;
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
public static Socket clientSocket = null;
public static ObjectInputStream objectInputStream = null;
public static ObjectOutputStream objectOutputStream = null;
private static ActionBarActivity thisActivity;
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
thisActivity = this;
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));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//checkForPermission();
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
returnAppropriateFragment(position + 1)).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
}
my app crash and send me this bug report on my phone
main_activity.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.remotelab.MainActivity" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/navigation_drawer"
android:name="com.example.remotecontrolpc.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
NavigationDrawerFragnent.java
package com.example.remotelab;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
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);
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState
.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
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);
}
});
NavigationDrawerItem navigationDrawerItems[] = new NavigationDrawerItem[] {
new NavigationDrawerItem(R.drawable.connect, getString(R.string.connect)),
new NavigationDrawerItem(R.drawable.touchpad, getString(R.string.touchpad)),
new NavigationDrawerItem(R.drawable.keyboard, getString(R.string.keyboard)),
new NavigationDrawerItem(R.drawable.file_transfer, getString(R.string.file_transfer)),
new NavigationDrawerItem(R.drawable.presentation, getString(R.string.presentation)),
new NavigationDrawerItem(R.drawable.power_off, getString(R.string.power_off))
};
mDrawerListView.setAdapter(new NavigationDrawerItemAdapter(getActionBar().getThemedContext(),
R.layout.listview_item_navigation_drawer, navigationDrawerItems));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null
&& mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(getActivity(),
mDrawerLayout,
R.drawable.ic_drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true)
.apply();
}
getActivity().supportInvalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
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);.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
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);
}
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();
}
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
}
Got The Bug
You Have To Remove All Unwanted Code From Android's Default Fragment Creation's.
Take Backup Of NavigationDrawerFragment File and Replace Below NavigationDrawerFragment with your NavigationDrawerFragment File.
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class NavigationDrawerFragment extends Fragment {
private Context mContext;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mContext = view.getContext();
initialiseView(view);
return view;
}
private void initialiseView(View view) {
//DO ANY INSTANCE VARIABLE INITIALISATION
}
}
I am developing an application where i have to display a navigation drawer in home page.I am using NavigationView where i will point which menu it should populate.Now what problem i am facing is, its displaying items twice.Below code will show you what i have done so far
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.mylaw.rkme3.mylawproject.fragments.HomeFragment;
import com.mylaw.rkme3.mylawproject.fragments.VideoHomeFragment;
import com.mylaw.rkme3.mylawproject.interfaces.FragmentInterface;
import com.mylaw.rkme3.mylawproject.utils.Constants;
/**
* Created by Lincy on 7/4/2016.
**/
public class MainActivity extends AppCompatActivity implements FragmentInterface {
private static final String TAG = "MainActivity";
private Toolbar mToolBar;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
displayScreens();
}
private void initView() {
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mToolBar = (Toolbar) findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
setUpNavigationDrawer();
mNavigationView.inflateMenu(R.menu.drawer);
}
private void setUpNavigationDrawer() {
setSupportActionBar(mToolBar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, mToolBar,
R.string.openDrawer,
R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
if (item.isChecked())
item.setChecked(false);
else item.setChecked(true);
mDrawerLayout.closeDrawers();
switch (item.getItemId()) {
case R.id.sub_item_in_progress:
goToInProgress();
return true;
case R.id.sub_item_completed:
goToCompleted();
return true;
case R.id.sub_lapsed:
goToLapsed();
return true;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
});
}
private void goToLapsed() {
Intent courseLapsedIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "Lapsed");
courseLapsedIntent.putExtras(extras);
startActivity(courseLapsedIntent);
}
private void goToCompleted() {
Intent courseCompletedIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "Completed");
courseCompletedIntent.putExtras(extras);
startActivity(courseCompletedIntent);
}
private void goToInProgress() {
Intent courseProgressIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "InProgress");
courseProgressIntent.putExtras(extras);
startActivity(courseProgressIntent);
}
private void displayScreens() {
this.action(Constants.FragmentInterfaceConstants.ACTION_HOME, null);
}
#Override
public void action(int tag, Bundle args) {
switch (tag) {
case Constants.FragmentInterfaceConstants.ACTION_HOME:
handleHomeScreen();
break;
case Constants.FragmentInterfaceConstants.ACTION_VIDEO_HOME:
handleVideoHomeScreen();
break;
default:
break;
}
}
#Override
public void showActionBar(boolean show) {
}
#Override
public void showHomeButton(boolean show) {
}
#Override
public void setActionBarTitle(String title) {
}
private void handleHomeScreen() {
HomeFragment homeFragment = new HomeFragment();
addFragment(homeFragment, HomeFragment.TAG);
}
private void handleVideoHomeScreen() {
VideoHomeFragment videoHomeFragment = new VideoHomeFragment();
addFragment(videoHomeFragment, HomeFragment.TAG);
}
private void addFragment(Fragment fragment, String tag) {
FragmentTransaction ft =
getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(tag);
ft.commitAllowingStateLoss();
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
}else {
getSupportFragmentManager().popBackStack();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_Register:
Intent registerIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle extras = new Bundle();
extras.putString("fragName", "Register");
registerIntent.putExtras(extras);
startActivity(registerIntent);
break;
case R.id.item_search:
Intent searchIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle searchExtras = new Bundle();
searchExtras.putString("fragName", "Search");
searchIntent.putExtras(searchExtras);
startActivity(searchIntent);
break;
case R.id.item_login:
Intent loginIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle loginExtras = new Bundle();
loginExtras.putString("fragName", "Login");
loginIntent.putExtras(loginExtras);
startActivity(loginIntent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
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.
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
I am trying to understand how to implement the ActionBarSherlock Navigation Drawer into a project. I have one working with the official Android implementation but I would like it to run at 2.2+ so I am looking into ActionBarSherlock. I have an error under the selectItem(int position) section of the code. I will paste it here:
package com.rufflez.absnavdrawer;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mFragmentTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mFragmentTitles = getResources().getStringArray(R.array.fragments);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(R.id.drawer_list);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mFragmentTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View v){
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null){
selectItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu){
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
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;
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, Sources.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
selectItem(position);
}
}
private void selectItem(int position){
Fragment newFragment = new Fragment_1();
FragmentManager fm = getSupportFragmentManager();
switch(position){
case 0:
newFragment = new Fragment_1();
break;
case 1:
newFragment = new Fragment_2();
break;
case 2:
newFragment = new Fragment_3();
break;
case 3:
newFragment = new Fragment_4();
break;
case 4:
newFragment = new Fragment_5();
break;
}
fm.beginTransaction()
.replace(R.id.content_frame, newFragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mFragmentTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title){
mTitle = title;
getSupportActionBar().setTitle(title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
As I said above, the error is under selectItem and specifically error under new Fragment_1(); and again at new Fragment_1();. The eclipse message is Type mismatch: cannot convert from Fragment_1 to Fragment.
This is Fragment_1.java:
package com.rufflez.absnavdrawer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class Fragment_1 extends FragmentActivity{
WebView webview;
private String url;
ProgressBar pd = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// pd = (ProgressBar) findViewById(R.id.web_view_progress_bar);
// webview = (WebView) findViewById(R.id.WebView);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && pd.getVisibility() == View.GONE){
pd.setVisibility(View.VISIBLE);
}
pd.setProgress(progress);
if(progress == 100) {
pd.setVisibility(View.GONE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
// then it is not handled by default action
}
});
webview.loadUrl("file:///android_asset/about.html");
}
#Override
public void onBackPressed()
{
if(webview.canGoBack())
webview.goBack();
else
super.onBackPressed();
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
I think you are missing a cast, since new Fragment_1() will return class Fragment_1, and not Fragment.
Oh! Fragment_1() is FragmentActivity Which is an Activity different from Fragment!
see it
Dilemma: when to use Fragments vs Activities:
Your fragment isn't a fragment.
Change onCreate to onCreateView and do this code;
public class Fragment_1 extends SherlockFragment{
i think that is the error.
if not, try rebuilding your fragment in this one
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.frag1, container, false);
//change frag1 to corresponding XML
}
}