so what i am trying is if the DrawerLayout is open and than i rotated the screen the DrawerLayout should close , but it does not
here is the code
package com.moammedx.learingmaterial;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
public class NavigationDrwaerFragment extends Fragment {
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learnd_drawer";
private View contenerView;
private ActionBarDrawerToggle mDrawerTolggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
public NavigationDrwaerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_navigation_drwaer, container, false);
}
public void SetUp(int fragmenID, DrawerLayout drawerlayout, Toolbar toolbar) {
contenerView = getActivity().findViewById(fragmenID);
mDrawerLayout = drawerlayout;
mDrawerTolggle = new ActionBarDrawerToggle(getActivity(), drawerlayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
if (!mUserLearnedDrawer) {
super.onDrawerOpened(drawerView);
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
Toast.makeText(getActivity(), "onDrawerClosed", Toast.LENGTH_SHORT).show();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(contenerView);
}
if (mFromSavedInstanceState) {
Toast.makeText(getActivity(), "close now", Toast.LENGTH_SHORT).show();
mDrawerLayout.closeDrawer(contenerView);
}
mDrawerLayout.setDrawerListener(mDrawerTolggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerTolggle.syncState();
}
});
}
public static void saveToPreferences(Context context, String preferencesName, String preferencesValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferencesName, preferencesValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferencesName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferencesName, defaultValue);
}
}
the SetUp method is called from the main activity
In the onCreat i checked of savedInstanceState is exist
and later inside the SetUp i used .colseDrawer to close the DrawerLayout , but it does not close , and i added for toast just for test and it show up when i rotate the screen
The reason is because the inner workings of the DrawerLayout close command is not wrapped in a post runnable. Meaning, your close command will fire, but before it's state saving kicks in and returns it to it's previous state (in this case open). To fix from your code, simply wrap the contents of your close command in a post runnable. It'll execute after the onCreate() and onRestoreState() are called, closing your drawer on rotation.
Will i solve it by adding .closeDrawer in onResume
public void onResume() {
super.onResume();
mDrawerLayout.closeDrawer(contenerView);
}
It is better to close it on onRestoreInstanceState
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
mDrawerLayout.closeDrawer(GravityCompat.START, false)
}
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
}
}
my app has no error yet it is showing an error "unfortunately zine has stopped"
main activity.java
package piestudio.zine;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends ActionBarActivity{
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUP((DrawerLayout) findViewById(R.id.drawer_layout),toolbar);
}
}
`
navigation drawer activity
package piestudio.zine;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class NavigationDrawerFragment extends Fragment {
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER="user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer=Boolean.valueOf(readFromPreferences(getActivity(),KEY_USER_LEARNED_DRAWER,"false"));
if(savedInstanceState!=null){
mFromSavedInstanceState=true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
}
public void setUP(DrawerLayout drawerLayout, Toolbar toolbar) {
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName,defaultValue);
}
}
now as you can see the code , now whenever i try to run this on my phone (as my emulator is not working ) it stops by saying ## unfortunatley,zine has stopped
Try changing this code
private Toolbar toolbar;
to this
android.support.v7.widget.Toolbar
and see whether the crash is happening or not. Please logcat output so that we can debug the crash in a better manner.
I would like that the title in the menu will change by the fragment name that was click. for the code below what i get is that, the actual title in each fragment is "Home" and its does not change. but i found that when i click on an item in the menu the title changing for a second and return back to the "Home" title. i implemented the ondrawer but still i don't know what could cause that.
my code:
package com.example.matant.gpsportclient;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.matant.gpsportclient.Controllers.Fragments.CreateEventFragmentController;
import com.example.matant.gpsportclient.Controllers.DBcontroller;
import com.example.matant.gpsportclient.Controllers.Fragments.GoogleMapFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ManageEventFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ProfileFragmentController;
import com.example.matant.gpsportclient.InterfacesAndConstants.AsyncResponse;
import com.example.matant.gpsportclient.InterfacesAndConstants.Constants;
import com.example.matant.gpsportclient.Utilities.DrawerItem;
import com.example.matant.gpsportclient.Utilities.DrawerItemCustomAdapter;
import com.example.matant.gpsportclient.Utilities.SessionManager;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainScreen extends AppCompatActivity implements AsyncResponse {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DBcontroller dbController;
private ProgressDialog progress = null;
private SessionManager sm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
return;
}
mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
sm = SessionManager.getInstance(this);
mTitle = mDrawerTitle = "Home";
DrawerItem [] drawerItems = new DrawerItem[Constants.MENU_SIZE];
drawerItems[0] = new DrawerItem(R.drawable.home,"Home");
drawerItems[1] = new DrawerItem(R.drawable.profile,"Profile");
drawerItems[2] = new DrawerItem(R.drawable.search,"Search Events");
drawerItems[3] = new DrawerItem(R.drawable.create,"Create Event");
drawerItems[4] = new DrawerItem(R.drawable.manage,"Manage Event");
drawerItems[5] = new DrawerItem(R.drawable.attending,"Attending List");
drawerItems[6] = new DrawerItem(R.drawable.recent_search_24,"Recent Searches");
drawerItems[7] = new DrawerItem(R.drawable.logout,"Log Out");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
getSupportActionBar().setTitle(mNavigationDrawerItemTitles[0]);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void handleResponse(String resStr) {
try
{
if((this.progress!= null )&& this.progress.isShowing())
{
this.progress.dismiss();
}
}catch (final IllegalArgumentException e){
Log.d("Dialog error",e.getMessage());
}catch (final Exception e){
Log.d("Dialog error",e.getMessage());
}
finally {
this.progress = null;
}
Log.d("handleResponse", resStr);
if(resStr!=null)
{
try {
JSONObject jsonObj = new JSONObject(resStr);
String flg = jsonObj.getString(Constants.TAG_FLG);
switch (flg) {
case "user logged out":
{
sm.logoutUser();
break;
}
case "query failed": {
Toast.makeText(getApplicationContext(),"Error Connection",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void sendDataToDBController() {
String user = sm.getUserDetails().get(Constants.TAG_EMAIL);
BasicNameValuePair tagReq = new BasicNameValuePair("tag","logout");
BasicNameValuePair userNameParam = new BasicNameValuePair("username",user);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(tagReq);
nameValuePairList.add(userNameParam);
dbController = new DBcontroller(this,this);
dbController.execute(nameValuePairList);
}
#Override
public void preProcess() {
this.progress = ProgressDialog.show(this, "Log Out",
"Logging out...", true,false);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0: //Home
fragment = new GoogleMapFragmentController();
break;
case 1: //Profile
fragment = new ProfileFragmentController();
break;
case 2: //Search Events
//fragment = new SearchEventFragmentController();
break;
case 3: //Create Events
fragment = new CreateEventFragmentController();
break;
case 4: //Manage Events
fragment = new ManageEventFragmentController();
break;
case 5: //Attending List
//fragment = new AttendingListFragmentController();
break;
case 6: //Recent Searches
//fragment = new RecentSearchesFragmentController();
break;
case 7: { //Log Out
logout();
finish(); //destroy the main activity
}
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
getSupportActionBar().setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().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);
}
public void logout()
{
sendDataToDBController();
}
/*#Override
protected void onDestroy() {
super.onDestroy();
logout();
}*/
}
Set it for all your fragment. This should do the work!!
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.id.your_fragment_layout, container,
false);
getActivity().setTitle("<your title>");
return rootView;
}
try this:
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Your Title");
}
Ok i found the problem, your answer was good and i really change the title each time from the fragment but in addition i need to disable this line:
getSupportActionBar().setTitle(mDrawerTitle);
from the onDrawerOpened and onDrawerClosed
Do not set the title to ActionBar, set the title to Activity, you can do so from the activity or fragment.
For Activity:
setTitle("New Title");
or for Fragment:
getActivity().setTitle("New Title");
add this in your fragment
getActivity().setTitle("title");
add remove this below line from Drawer activity
getActivity().setTitle("title");
Try this one it worked for me
place a Textview inside the toolbar of app_bar activity
Inside the oncreateView of a fragment put this code
TextView heading;
heading=(TextView)getActivity().findViewById(R.id.Id_title);
heading.setText("your text");
By using this you can Name each fragments with your own text
In onCreateView()write following code:
activity!!.setTitle("Your Text")
If your purpose is "Changing toolbar title according to the fragment name"
i tip to see if the "navigation graph" of the "navigation drawer" you set all stuff correctly: every fragment should have something like this:
<fragment
android:id="#+id/nav_ID_OF_FRAGMENT"
android:name="rubik_cube.navigation.ui.NAME_OF_Fragment"
android:label="#string/TOOLBAR_TITLE_HERE"
tools:layout="#layout/fragment_LAYOUT_GO_HERE" />
and in the resources the fragment desired title string,
in the res/layout the layout of the fragment,
in the code a class that handle the fragment stuff
and toolbar works perfectly!
if u want to change toolbar name dinamically according to other stuff like idk pressing a button, select from menu u need to change it programmatically instead with:
ActionBar toolbar = requireActivity().getSupportActionBar();
if(toolbar != null) toolbar.setTitle("your title");
navigation drawer not responding to clicks and snack is also not showing up.
how to make the clicks responsive and add fragments for data loading.
their are two items in the drawer and only one gets checked at the time of selection.
package com.example.jasaran.nav;
import com.example.jasaran.nav.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
private FrameLayout mContentFrame;
private int mCurrentSelectedPosition;
private static final String PREFERENCES_FILE = "nav_settings";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mUserLearnedDrawer;
int mselected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpToolbar();
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(this, PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
boolean mFromSavedInstanceState = true;
}
setUpNavDrawer();
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mContentFrame = (FrameLayout) findViewById(R.id.nav_contentframe);
mNavigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
Menu menu = mNavigationView.getMenu();
menu.getItem(mCurrentSelectedPosition).setChecked(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
}
private void setUpNavDrawer() {
if (mToolbar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_launcher);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
if (!mUserLearnedDrawer) {
mDrawerLayout.openDrawer(GravityCompat.START);
mUserLearnedDrawer = true;
saveSharedSetting(this, PREF_USER_LEARNED_DRAWER, "true");
}
}
public static void saveSharedSetting(Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting(Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mselected = menuItem.getItemId();
switch (menuItem.getItemId()) {
case R.id.navigation_item_1:
Snackbar.make(mContentFrame, "Item One", Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
return true;
case R.id.navigation_item_2:
Snackbar.make(mContentFrame, "Item Two", Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
return true;
default:
return true;
}
}
}
I see you've implemented the listener directly from the Activity. Try attaching it to the NavigationView like this:
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Handle menu clicks here
}
});
Check this Activity code on GitHub.
I cannot find out what the problem is here! I am following this tutorial for building a navigation drawer with fragments and I cannot find a way to fix the "cannot resolve symbol error". The error is on "drawer_nav_item". I have looked for unused classes and other times that it is used and cannot find it! Please Help! I can provide more code upon request
This is my activity_main.xml
package com.nhscoding.safe2tell;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import com.nhscoding.safe2tell.AboutClass;
import com.nhscoding.safe2tell.FragmentNavigationDrawer;
import com.nhscoding.safe2tell.LearnClass;
import com.nhscoding.safe2tell.R;
import com.nhscoding.safe2tell.SettingsClass;
import com.nhscoding.safe2tell.StoriesClass;
import com.nhscoding.safe2tell.SubmitClass;
public class MainActivity extends FragmentActivity {
private FragmentNavigationDrawer dlDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find our drawer view
dlDrawer = (FragmentNavigationDrawer) findViewById(R.id.drawer_layout);
// Setup drawer view
dlDrawer.setupDrawerConfiguration((ListView) findViewById(R.id.lvDrawer),
R.layout.drawer_nav_item, R.id.flContent);
// Add nav items
dlDrawer.addNavItem("Submit", "Submit Class", SubmitClass.class);
dlDrawer.addNavItem("Second", "Second Fragment", StoriesClass.class);
dlDrawer.addNavItem("Third", "Third Fragment", LearnClass.class);
dlDrawer.addNavItem("Fouth", "Fourth Fragment", AboutClass.class);
dlDrawer.addNavItem("Fifth", "Fifth Fragment", SettingsClass.class);
// Select default
if (savedInstanceState == null) {
dlDrawer.selectDrawerItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
if (dlDrawer.isDrawerOpen()) {
// Uncomment to hide menu items
// menu.findItem(R.id.mi_test).setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Uncomment to inflate menu items to Action Bar
// inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (dlDrawer.getDrawerToggle().onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
dlDrawer.getDrawerToggle().syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
dlDrawer.getDrawerToggle().onConfigurationChanged(newConfig);
}
}
Here is my Navigation Drawer Class
package com.nhscoding.safe2tell;
import java.util.ArrayList;
import android.content.Context;
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.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.nhscoding.safe2tell.R;
public class FragmentNavigationDrawer extends DrawerLayout {
private ActionBarDrawerToggle drawerToggle;
private ListView lvDrawer;
private ArrayAdapter<String> drawerAdapter;
private ArrayList<FragmentNavItem> drawerNavItems;
private int drawerContainerRes;
public FragmentNavigationDrawer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public FragmentNavigationDrawer(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FragmentNavigationDrawer(Context context) {
super(context);
}
// setupDrawerConfiguration((ListView) findViewById(R.id.lvDrawer), R.layout.drawer_list_item, R.id.flContent);
public void setupDrawerConfiguration(ListView drawerListView, int drawerItemRes, int drawerContainerRes) {
// Setup navigation items array
drawerNavItems = new ArrayList<FragmentNavigationDrawer.FragmentNavItem>();
// Set the adapter for the list view
drawerAdapter = new ArrayAdapter<String>(getActivity(), drawerItemRes,
new ArrayList<String>());
this.drawerContainerRes = drawerContainerRes;
// Setup drawer list view and related adapter
lvDrawer = drawerListView;
lvDrawer.setAdapter(drawerAdapter);
// Setup item listener
lvDrawer.setOnItemClickListener(new FragmentDrawerItemListener());
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
drawerToggle = setupDrawerToggle();
setDrawerListener(drawerToggle);
// set a custom shadow that overlays the main content when the drawer
setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// Setup action buttons
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
// addNavItem("First", "First Fragment", FirstFragment.class)
public void addNavItem(String navTitle, String windowTitle, Class<? extends Fragment> fragmentClass) {
drawerAdapter.add(navTitle);
drawerNavItems.add(new FragmentNavItem(windowTitle, fragmentClass));
}
/** Swaps fragments in the main content view */
public void selectDrawerItem(int position) {
// Create a new fragment and specify the planet to show based on
// position
FragmentNavItem navItem = drawerNavItems.get(position);
Fragment fragment = null;
try {
fragment = navItem.getFragmentClass().newInstance();
Bundle args = navItem.getFragmentArgs();
if (args != null) {
fragment.setArguments(args);
}
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(drawerContainerRes, fragment).commit();
// Highlight the selected item, update the title, and close the drawer
lvDrawer.setItemChecked(position, true);
setTitle(navItem.getTitle());
closeDrawer(lvDrawer);
}
public ActionBarDrawerToggle getDrawerToggle() {
return drawerToggle;
}
private FragmentActivity getActivity() {
return (FragmentActivity) getContext();
}
private ActionBar getSupportActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
private void setTitle(CharSequence title) {
getSupportActionBar().setTitle(title);
}
private class FragmentDrawerItemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectDrawerItem(position);
}
}
private class FragmentNavItem {
private Class<? extends Fragment> fragmentClass;
private String title;
private Bundle fragmentArgs;
public FragmentNavItem(String title, Class<? extends Fragment> fragmentClass) {
this(title, fragmentClass, null);
}
public FragmentNavItem(String title, Class<? extends Fragment> fragmentClass, Bundle args) {
this.fragmentClass = fragmentClass;
this.fragmentArgs = args;
this.title = title;
}
public Class<? extends Fragment> getFragmentClass() {
return fragmentClass;
}
public String getTitle() {
return title;
}
public Bundle getFragmentArgs() {
return fragmentArgs;
}
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(getActivity(), /* host Activity */
this, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
// setTitle(getCurrentTitle());
// call onPrepareOptionsMenu()
getActivity().supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
// setTitle("Navigate");
// call onPrepareOptionsMenu()
getActivity().supportInvalidateOptionsMenu();
}
};
}
public boolean isDrawerOpen() {
return isDrawerOpen(lvDrawer);
}
}
The issue is that you have not defined your layout: drawer_nav_item
#Override
public void onCreate(Bundle sIS){
super(sIS);
setContentView(R.layout.activity_main);
// Find our drawer view
dlDrawer = (FragmentNavigationDrawer) findViewById(R.id.drawer_layout);
// Setup drawer view
dlDrawer.setupDrawerConfiguration((ListView)findViewById(R.id.lvDrawer),
R.layout.drawer_nav_item, /* <- this layout has not been defined
in your layouts folder */
R.id.flContent);
...
}