I have an app in which I have a navigation panel with menu buttons on which I want to apply navigation drawer, currently it takes up the entire screen,but I want to restrict it to 3/4th of the screen by applying navigation drawer on it, but i have never touched navigation drawer before so have no clue, any help or guidance will be great.Also went through some documentation and got confused :(
Here is my code:
and here is my layout class for navigation panel:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/com.justin.a"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_texture"
android:clickable="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/nav_margin"
android:layout_marginTop="#dimen/nav_margin"
android:layout_marginRight="#dimen/nav_margin"
android:layout_marginBottom="#dimen/nav_margin"
android:background="#242424"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/nav_padding"
android:paddingTop="#dimen/nav_padding"
android:paddingRight="#dimen/nav_padding"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#android:drawable/divider_horizontal_bright"
android:orientation="vertical"
android:showDividers="middle"
>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_dashboard"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:layout_marginBottom="1px"
android:onClick="onDashboardClicked"
android:text="#string/nav_option_dashboard"
android:textSize="#dimen/navigation_panel_text"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_news"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
foo:customFont="cabin.medium.ttf"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:onClick="onNewsClicked"
android:text="#string/nav_option_news"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_markets"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:onClick="onMarketClicked"
android:text="#string/nav_option_markets"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_lists"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:text="#string/nav_option_lists"
foo:customFont="cabin.medium.ttf"
android:onClick="onListsClicked"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<!-- UncommentForAlerts- Remove android:visibility="gone" -->
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_alerts"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:onClick="onAlertsClicked"
android:text="#string/nav_option_alerts"
android:background="#drawable/nav_background_button"
android:visibility="gone"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_briefcase"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:onClick="onBriefcaseClicked"
android:text="#string/nav_option_briefcase"
android:background="#drawable/nav_background_button"
/>
</LinearLayout>
</ScrollView>
<ImageButton
android:id="#+id/button_information"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_centerHorizontal="true"
/>
<ImageButton
android:id="#+id/button_settings"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_toLeftOf="#+id/button_information" />
<ImageButton
android:id="#+id/button_logout"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_toRightOf="#+id/button_information"
/>
</RelativeLayout>
</RelativeLayout>
Also here is my navigationpanelfragment.java:
--UPDATE----
public class NavigationPanelFragment extends Fragment implements OnClickListener {
public static final String TAG_NAVIGATION_PANEL_FRAGMENT = "NavigationPanelFragment";
public static final String ACTIVE_MENU_ITEM = "ActiveMenuItem";
private ActionBarDrawerToggle drawerToggle;
private Fragment lvDrawer;
public static void newInstance(final FragmentManager manager, final String activeFragmentTag) {
final NavigationPanelFragment fragment = new NavigationPanelFragment();
final Bundle arguments = new Bundle();
arguments.putString(NavigationPanelFragment.ACTIVE_MENU_ITEM, activeFragmentTag);
fragment.setArguments(arguments);
final FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD);
fragmentInfo.setAnimation(R.anim.slide_in_from_left, FragmentInfo.NO_ANIMATION);
fragmentInfo.setPopAnimation(0, R.anim.slide_out_to_left);
fragmentInfo.setFragmentTag(TAG_NAVIGATION_PANEL_FRAGMENT);
fragmentInfo.doNotAddToBackStack();
fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.title_applications));
FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
}
public static void removeInstance(final FragmentManager manager) {
Fragment fragment = manager.findFragmentByTag(TAG_NAVIGATION_PANEL_FRAGMENT);
if (fragment == null) {
return;
}
manager.beginTransaction().setCustomAnimations(0, R.anim.slide_out_to_left).remove(fragment).commitAllowingStateLoss();
}
private LogoutListener mLogoutListener = new LogoutListener() {
#Override
public void onLogoutOperationFired() {
final Activity activity = getActivity();
if(activity != null){
LoginActivity.newInstance(activity);
UserProfileManager.clearUserProfileManager();
FragmentStackManager.getInstance().clearBackStack(getFragmentManager());
activity.finish();
}
}
};
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View view = inflater.inflate(R.layout.fragment_navigation_panel, container, false);
return view;
}
#SuppressWarnings("deprecation")
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ImageButton logoutButton = (ImageButton) getView().findViewById(R.id.button_logout);
logoutButton.setOnClickListener(this);
logoutButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_signout_nav_panel));
final ImageButton infoButton = (ImageButton) getView().findViewById(R.id.button_information);
infoButton.setOnClickListener(this);
infoButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_info_nav_panel));
final ImageButton settingsButton = (ImageButton) getView().findViewById(R.id.button_settings);
settingsButton.setOnClickListener(this);
settingsButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_prefs_nav_panel));
highlightActiveMenuItem();
}
#Override
public void onDestroy() {
super.onDestroy();
mLogoutListener = null;
}
#Override
public void onResume() {
MenuUtils.disableSearchMenu(getActivity());
MenuUtils.disableAlertMenu(getActivity());
super.onResume();
}
#Override
public void onPause() {
MenuUtils.enableSearchMenu(getActivity());
MenuUtils.enableAlertMenu(getActivity());
super.onPause();
}
#Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.button_logout:
final DialogFragment dialog = new LogoutCancelSignoutDialogFragment(mLogoutListener);
dialog.show(getActivity().getSupportFragmentManager(), AbsBaseaActivity.TAG_LOGOUT_DIALOG);
\ break;
case R.id.button_information:
leaveMainActivity();
InformationActivity.newInstance(getActivity());
\ break;
case R.id.button_settings:
leaveMainActivity();
PreferencesActivity.newInstance(getActivity());
\ break;
}
}
public ActionBarDrawerToggle getDrawerToggle() {
return drawerToggle;
}
private void leaveMainActivity() {
removeInstance(getActivity().getSupportFragmentManager());
final MainActivity activity = (MainActivity) getActivity();
activity.setNavigationOpen(false);
}
private void highlightActiveMenuItem() {
TextView highlightedTextView = null;
final String activeFragmentTitle = "";//getArguments().getString(ACTIVE_MENU_ITEM);
final Resources resources = Application.getAppResources();
if (resources.getString(R.string.nav_option_news).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_news);
} else if (resources.getString(R.string.nav_option_markets).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_markets);
} else if (resources.getString(R.string.nav_option_lists).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_lists);
} else if (resources.getString(R.string.nav_option_alerts).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_alerts);
}
else if (resources.getString(R.string.nav_option_briefcase).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_briefcase);
} else {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_dashboard);
}
highlightedTextView.setTextColor(getResources().getColor(R.color.dark_orange));
}
}
Here is my acitvity_main.xml (it works, shows a blank panel on swipe)
<?xml version="1.0" encoding="utf-8"?>
<!-- <include layout="#layout/main_title"/> -->
<!-- <Button android:text="Main" android:layout_height="wrap_content"
android:id="#+id/btn_refreshbtn_refresh" android:layout_width="wrap_content">
</Button> -->
<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=".MainActivity" >
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2">
</FrameLayout>
<fragment
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#666"
android:dividerHeight="1dp"
android:background="#333"
android:paddingLeft="15sp"
android:paddingRight="15sp"
android:name="com.justin.jar.fragments.NavigationPanelFragment"/>
</android.support.v4.widget.DrawerLayout>
----UPDATED----
Also here is my mainactivity.java (it has the navigation panel reference which i need to add under navigation drawer):
public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
public static final int REQUEST_CODE_LIST = 100;
private boolean mIsNavigationOpen = false;
private DrawerLayout drawerLayout;
private NavigationPanelFragment dlDrawer;
private ActionBarDrawerToggle actionBarDrawerToggle;
private boolean mIsSearchBarActive;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
public boolean isNavigationOpen() {
return mIsNavigationOpen;
}
#SuppressWarnings("deprecation")
public void setNavigationOpen(final boolean isNavigationOpen) {
this.mIsNavigationOpen = isNavigationOpen;
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
if(isNavigationOpen) {
mainButton.setBackgroundResource(R.drawable.bg_helios_active);
} else {
mainButton.setBackgroundDrawable(null);
}
}
public static void newInstance(final Activity activity) {
final Intent intent = new Intent(activity, MainActivity.class);
activity.startActivity(intent);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// 2. App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// 2.1 create ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close);
// 2.2 Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
initiateMainActionBar();
final FragmentManager supportFragmentManager = getSupportFragmentManager();
supportFragmentManager.addOnBackStackChangedListener(this);
if (savedInstanceState == null) {
mActiveFragment = DashboardFragment.getInstanceWithTransition(supportFragmentManager);
} else {
//resetToDashboard(supportFragmentManager);
}
//setup drawer
/* Set up the drawer toggle */
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle("");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#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((android.view.MenuItem) item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
private void setupOnClickListenerForMainButton() {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
toggleNavigationPanel();
}
});
}
#Override
public void manageActionBar() {
setTitle(null);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggleNavigationPanel();
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onResume() {
final IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastActions.USER_PROFILE);
filter.addAction(BroadcastActions.NEWS_IMAGE);
filter.addAction(BroadcastActions.NEWS_HEADLINES);
registerReceiver(mMainActivityReceiver, filter);
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(mMainActivityReceiver);
super.onPause();
BangoAgent.onIdle();
}
public void pushNewsArticlePagerFragment(final int position, final String selectedCategoryCode, final boolean isMyNews) {
NewsArticlePagerFragment.newInstance(getSupportFragmentManager(), position, selectedCategoryCode, isMyNews);
}
public void onDashboardClicked(final View view) {
toggleNavigationPanel();
if (isFragmentVisible(DashboardFragment.TAG_DASHBOARD_FRAGMENT)) {
return;
}
final FragmentManager manager = getSupportFragmentManager();
final FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = DashboardFragment.getInstance();
transaction.hide(mActiveFragment);
transaction.show(mActiveFragment);
transaction.commitAllowingStateLoss();
updateActionBarTitle();
}
public void onNewsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onMarketClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(MarketsFragment.TAG_MARKETS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = MarketsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onListsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onBriefcaseClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(BriefcaseFragment.TAG_BRIEFCASE_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = BriefcaseFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onAlertsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(AlertsContainerFragment.TAG_ALERTS_CONTAINER_FRAGMENT)){
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = AlertsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
private void toggleNavigationPanel() {
final FragmentStackManager manager = FragmentStackManager.getInstance();
if (mIsNavigationOpen) {
NavigationPanelFragment.removeInstance(getSupportFragmentManager());
updateActionBarTitle();
BangoHelper.eventMainNav();
} else {
final TextView title = (TextView) findViewById(R.id.main_title);
title.setText(getString(R.string.title_applications));
NavigationPanelFragment.newInstance(getSupportFragmentManager(), manager.getTopTitle());
}
setNavigationOpen(!mIsNavigationOpen);
}
public void updateActionBarTitle() {
final String title = FragmentStackManager.getInstance().getTopTitle();
final TextView titleView = (TextView) findViewById(R.id.main_title);
titleView.setText(title);
}
private boolean isFragmentVisible(final String tag) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
return fragment != null && tag.equals(fragment.getTag());
}
public interface BackPressListener<T extends Fragment> {
public boolean backPressed(MainActivity fragmentActivity);
}
private BackPressListener<Fragment> backPressListener = null;
public void setBackPressListener (final BackPressListener<Fragment> backPressListener) {
this.backPressListener = backPressListener;
}
#Override
public void onBackPressed() {
if (backPressListener != null) {
boolean b = false;
// Making sure we trigger the backPressed event if the listener is the top fragment
String bplTag = ((Fragment)backPressListener).getTag();
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
String topFragemtnTag = "";
if (topFragment != null) {
topFragemtnTag = topFragment.getTag();
}
if (mIsSearchBarActive) {
MenuUtils.hideSearchView(this);
mIsSearchBarActive = false;
} else if (mIsNavigationOpen) {
toggleNavigationPanel();
} else if (!FragmentStackManager.getInstance().popTopFragment()) {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
} else {
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
if (topFragment == null) {
mActiveFragment = DashboardFragment.getInstance();
((DashboardFragment)mActiveFragment).refreshDashboard();
} else if (topFragment instanceof AbsArticlePagerFragment) {
((AbsArticlePagerFragment) topFragment).forceUpdateTextSize();
} else if (topFragment instanceof AbsBaseArticleFragment) {
((AbsBaseArticleFragment) topFragment).forceUpdateTextSize();
}
}
updateActionBarTitle();
}
public void setActiveFragment(final Fragment fragment) {
mActiveFragment = fragment;
}
public void setIsSearchBarActive(final boolean isSearchBarActive){
mIsSearchBarActive = isSearchBarActive;
}
#Override
public void onBackStackChanged() {
for (int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++) {
final BackStackEntry bse = getSupportFragmentManager().getBackStackEntryAt(i);
Log.d("BackStack", "Changed: " + bse.getName());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_LIST) {
if (resultCode == RESULT_OK) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment because dashboard was never added to backstack
DashboardFragment.getInstance().onUpdate();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).onUpdate();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).onUpdate(data);
}
}
}
}
#Override
public void refreshScreen() {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment
DashboardFragment.getInstance().refreshScreen();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).refreshScreen();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).refreshScreen();
} else if (fragment instanceof MarketsFragment) {
((MarketsFragment) fragment).refreshScreen();
}else if (fragment instanceof AlertsContainerFragment) {
((AlertsContainerFragment) fragment).refreshScreen();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
dlDrawer.getDrawerToggle().onConfigurationChanged(newConfig);
}
}
This is a good article to follow for adding a navigation drawer: http://developer.android.com/training/implementing-navigation/nav-drawer.html
Your navigation drawer is showing a blank panel, because the drawer view in your activity_main.xml is a ListView (which you haven't set any data to).
You want to make this view your fragment.
Your activity_main.xml file should look like. Make sure to replace the class on the fragment tag to the correct class of your navigation fragment.
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity" >
<!-- This fragment container is your the place to put your activities content -->
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2" />
<!--
This is your navigation drawer. You can adjust the width here, but it should
be between 240dp and 320dp
-->
<fragment
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
class="com.yourapp.NavigationPanelFragment" />
</android.support.v4.widget.DrawerLayout>
Your MainActivity should look something like this:
public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
public static final int REQUEST_CODE_LIST = 100;
private Fragment mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
public boolean isNavigationOpen() {
return mDrawerLayout.isDrawerOpen(mDrawer);
}
#SuppressWarnings("deprecation")
public void setNavigationOpen(final boolean isNavigationOpen) {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
if(isNavigationOpen) {
mainButton.setBackgroundResource(R.drawable.bg_helios_active);
} else {
mainButton.setBackgroundDrawable(null);
}
}
public static void newInstance(final Activity activity) {
final Intent intent = new Intent(activity, MainActivity.class);
activity.startActivity(intent);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
initiateMainActionBar();
final FragmentManager supportFragmentManager = getSupportFragmentManager();
supportFragmentManager.addOnBackStackChangedListener(this);
if (savedInstanceState == null) {
mActiveFragment = DashboardFragment.getInstanceWithTransition(supportFragmentManager);
BangoHelper.onStartSession(this);
} else {
resetToDashboard(supportFragmentManager);
}
//setup drawer
//this is our drawer layout that contains the navigation drawer and your content
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//this is the navigation drawer fragment
mDrawer = (NavigationPanelFragment) findViewById(R.id.drawer);
}
private void resetToDashboard(final FragmentManager supportFragmentManager) {
FragmentStackManager.getInstance().clearBackStack(supportFragmentManager);
mActiveFragment = DashboardFragment.getInstanceWithNoTransition(supportFragmentManager);
}
private void initiateMainActionBar() {
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.actionbar_main);
setupOnClickListenerForSearchButton(this);
setupOnClickListenerForMainButton();
setupOnClickListenerForSearchCancelButton(this);
setupOnClickListenerForSearchClearButton(this);
}
private void setupOnClickListenerForSearchCancelButton(final MainActivity activity) {
final Button cancelButton = (Button) findViewById(R.id.button_search_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
final View actionBarView = findViewById(R.id.action_bar_container);
mIsSearchBarActive = MenuUtils.changeActionBar(activity, actionBarView);
}
});
}
private void setupOnClickListenerForMainButton() {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
toggleNavigationPanel();
}
});
}
#Override
public void manageActionBar() {
setTitle(null);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggleNavigationPanel();
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onResume() {
final IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastActions.USER_PROFILE);
filter.addAction(BroadcastActions.NEWS_IMAGE);
filter.addAction(BroadcastActions.NEWS_HEADLINES);
registerReceiver(mMainActivityReceiver, filter);
BangoAgent.onResume();
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(mMainActivityReceiver);
super.onPause();
saveTextSize();
}
private void saveTextSize() {
final ContentResolver resolver = EikonApplication.getAppContext().getContentResolver();
final ContentValues contentValues = new ContentValues();
contentValues.put(GenericColumns.TEXT_SIZE, SharedPreferencesManager.getInstance().getTextSize().ordinal());
SqlArguments argument = SqlArgumentsFactory.generateUserProfileUpdateSqlArguments();
String where = argument.getWhereClause();
String[] whereArgs = argument.getWhereArgs();
resolver.update(UserProfileContentProvider.USER_PROFILE_URI, contentValues, where, whereArgs);
}
public void pushNewsArticlePagerFragment(final int position, final String selectedCategoryCode, final boolean isMyNews) {
NewsArticlePagerFragment.newInstance(getSupportFragmentManager(), position, selectedCategoryCode, isMyNews);
}
public void onDashboardClicked(final View view) {
toggleNavigationPanel();
if (isFragmentVisible(DashboardFragment.TAG_DASHBOARD_FRAGMENT)) {
return;
}
final FragmentManager manager = getSupportFragmentManager();
final FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = DashboardFragment.getInstance();
transaction.hide(mActiveFragment);
transaction.show(mActiveFragment);
transaction.commitAllowingStateLoss();
updateActionBarTitle();
}
public void onNewsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onMarketClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(MarketsFragment.TAG_MARKETS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = MarketsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onListsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onBriefcaseClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(BriefcaseFragment.TAG_BRIEFCASE_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = BriefcaseFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onAlertsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(AlertsContainerFragment.TAG_ALERTS_CONTAINER_FRAGMENT)){
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = AlertsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
private void toggleNavigationPanel() {
if (mDrawerLayout.isDrawerOpen(mDrawer))
mDrawerLayout.closeDrawer(mDrawer);
else mDrawerLayout.openDrawer(mDrawer);
final FragmentStackManager manager = FragmentStackManager.getInstance();
setNavigationOpen(setNavigationOpen());
}
public void updateActionBarTitle() {
final String title = FragmentStackManager.getInstance().getTopTitle();
final TextView titleView = (TextView) findViewById(R.id.main_title);
titleView.setText(title);
}
private boolean isFragmentVisible(final String tag) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
return fragment != null && tag.equals(fragment.getTag());
}
public interface BackPressListener<T extends Fragment> {
public boolean backPressed(MainActivity fragmentActivity);
}
private BackPressListener<Fragment> backPressListener = null;
public void setBackPressListener (final BackPressListener<Fragment> backPressListener) {
this.backPressListener = backPressListener;
}
#Override
public void onBackPressed() {
BangoHelper.eventBack();
if (backPressListener != null) {
boolean b = false;
// Making sure we trigger the backPressed event if the listener is the top fragment
String bplTag = ((Fragment)backPressListener).getTag();
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
String topFragemtnTag = "";
if (topFragment != null) {
topFragemtnTag = topFragment.getTag();
if (bplTag != null && topFragemtnTag != null && bplTag.equals(topFragemtnTag)) {
b = backPressListener.backPressed(this);
}
}
if (b) {
return;
}
}
if (mIsSearchBarActive) {
MenuUtils.hideSearchView(this);
mIsSearchBarActive = false;
} else if (mIsNavigationOpen) {
toggleNavigationPanel();
} else if (!FragmentStackManager.getInstance().popTopFragment()) {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
} else {
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
if (topFragment == null) {
mActiveFragment = DashboardFragment.getInstance();
((DashboardFragment)mActiveFragment).refreshDashboard();
} else if (topFragment instanceof AbsArticlePagerFragment) {
((AbsArticlePagerFragment) topFragment).forceUpdateTextSize();
} else if (topFragment instanceof AbsBaseArticleFragment) {
((AbsBaseArticleFragment) topFragment).forceUpdateTextSize();
}
}
updateActionBarTitle();
}
public void setActiveFragment(final Fragment fragment) {
mActiveFragment = fragment;
}
public void setIsSearchBarActive(final boolean isSearchBarActive){
mIsSearchBarActive = isSearchBarActive;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_LIST) {
if (resultCode == RESULT_OK) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment because dashboard was never added to backstack
DashboardFragment.getInstance().onUpdate();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).onUpdate();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).onUpdate(data);
}else if (fragment instanceof AlertsContainerFragment) {
((AlertsContainerFragment) fragment).onUpdate();
}
}
}
}
#Override
public void refreshScreen() {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment
DashboardFragment.getInstance().refreshScreen();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).refreshScreen();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).refreshScreen();
} else if (fragment instanceof MarketsFragment) {
((MarketsFragment) fragment).refreshScreen();
}
}
#Override
public void retryLoginDelayedData(){
LoginFragment f = new LoginFragment();
f.login("delayed");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
FragmentStackManager stackManager = FragmentStackManager.getInstance();
Fragment topFragment = stackManager.getTopFragment();
if(topFragment != null){
if(topFragment instanceof ChartFragment){
ChartFragment.replaceInstance(((ChartFragment)topFragment), getSupportFragmentManager(), R.id.fragment_container);
}
}
}
}
Notice that the state of the navigation drawer is managed by the drawer layout. The DrawerLayout and the drawer fragment is bound up in the onCreate method.
Refer to the article i mentioned if you run into trouble.
--- EDIT ----
Below is an activity I have used in an app. It shows how to add the drawer toggle (the link I posted also shows this).
You should be able to merge this with your current activity and have a working navigation drawer.
public class SampleActivity extends AbsBaseaActivity {
private Fragment mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerMenuItems = getResources().getStringArray(R.array.home_menu_drawer_titles);
mDrawer = (fragment) findViewById(R.id.drawer);
/* Set up the drawer toggle */
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_closed) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle(R.string.activity_title);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
mDrawer.setItemChecked(0, true);
}
#Override public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawer)) {
mDrawerLayout.closeDrawer(mDrawer);
} else {
mDrawerLayout.openDrawer(mDrawer);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you are having errors, then post what the errors are.
U can get source ode for navigation drawer from the link below
http://hmkcode.com/android-creating-a-navigation-drawer/
copy this to workspace, or open as a new android project from existing source code.
right click on project > properties >java buildpath> add external jar> choose latest V13 support library from android sdks installed and in order and export tick the jar v13
again right click on project > properties >android>choose abs library. [google for library]
U will get error free working project
All the answer above are awesome but I found it little bit difficult to add it in my existing code so I have created a new class which uses animation and LayoutInflater to add view and removes the navigation drawer to the activity you can use it in fragment also.
NavigationDrawer.java
import android.app.Activity;
import android.support.constraint.ConstraintLayout;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
public class NavigationDrawer {
//State is the visible state
private Boolean state = false, Transition = false;
private ConstraintLayout mainView;
private ConstraintLayout navigationLayout;
private Animation show, hide;
public NavigationDrawer(Activity activity, ConstraintLayout view) {
this.mainView = view;
LayoutInflater layoutInflater = (LayoutInflater)
activity.getSystemService(LAYOUT_INFLATER_SERVICE);
navigationLayout = (ConstraintLayout) layoutInflater.inflate(R.layout.nav_drawer,
mainView, false);
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//Show animation
show = new TranslateAnimation(-displayMetrics.widthPixels, 0, 0, 0);
show.setDuration(500);
show.getFillAfter();
show.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Transition = true;
}
#Override
public void onAnimationEnd(Animation animation) {
Transition = false;
state = true;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
//Hide animation
hide = new TranslateAnimation(0, -displayMetrics.widthPixels, 0, 0);
hide.setDuration(500);
hide.getFillAfter();
hide.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Transition = true;
}
#Override
public void onAnimationEnd(Animation animation) {
Transition = false;
state = false;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
public void toggle() {
if (!Transition) {
if (!state) {
mainView.addView(navigationLayout);
navigationLayout.startAnimation(show);
} else {
navigationLayout.startAnimation(hide);
mainView.removeView(navigationLayout);
}
}
}
}
To use this class.
NavigationDrawer navigationDrawer = new
NavigationDrawer(this,user_activity_main_layout);
//To toggle it
navigationDrawer.toggle();
Here user_activity_main_layout is the Id of root ConstrainLayout you can choose whatever you want.
This works perfect.
Related
I am trying to do restoring the fragment view state values(text view,..etc) when back from second fragment in android bottom navigation view.
MyActivity.java
public class LandingPage extends AppCompatActivity implements ProductFragment.AddToCart {
Fragment fragment;
TextView txtCart;
Button btnCart;
ItemData itemData;
ArrayList<ItemData> itemDataList;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fragment = new ProductFragment();
loadFragment(fragment);
return true;
case R.id.nav_profile:
fragment = new ReportsFragment();
loadFragment(fragment);
return true;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing_page);
txtCart = findViewById(R.id.txt_cart);
btnCart = findViewById(R.id.btn_cartImg);
itemDataList = new ArrayList<>();
BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
loadFragment(new ProductFragment());
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
ProductFragment.java
public class ProductFragment extends Fragment {
private OnFragmentInteractionListener mListener;
Button btnCart1,btnCart2,btnCart3;
AddToCart addToCart;
TextView txtItem1Des,txtItem1Price,txtItem2Des,txtItem2Price,txtItem3Des,txtItem3Price;
Button btnCart1Inc,btnCart1Dec,btnCart2Inc,btnCart2Dec,btnCart3Inc,btnCart3Dec;
TextView cart1txt,cart2txt,cart3txt;
String itemDes,itemPrice,itemImg,itemCount;
int quantity1,quantity2,quantity3;
public ProductFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
btnCart1 = view.findViewById(R.id.cart1);
txtItem1Des = view.findViewById(R.id.cart1_desc);
txtItem1Price = view.findViewById(R.id.cart1_price);
btnCart1Inc = view.findViewById(R.id.cart1Inc);
btnCart1Dec = view.findViewById(R.id.cart1Dec);
cart1txt = view.findViewById(R.id.cart1txt);
btnCart2 = view.findViewById(R.id.cart2);
txtItem2Des = view.findViewById(R.id.cart2_desc);
txtItem2Price = view.findViewById(R.id.cart2_price);
btnCart2Inc = view.findViewById(R.id.cart2Inc);
btnCart2Dec = view.findViewById(R.id.cart2Dec);
cart2txt = view.findViewById(R.id.cart2txt);
btnCart3 = view.findViewById(R.id.cart3);
txtItem3Des = view.findViewById(R.id.cart3_desc);
txtItem3Price = view.findViewById(R.id.cart3_price);
btnCart3Inc = view.findViewById(R.id.cart3Inc);
btnCart3Dec = view.findViewById(R.id.cart3Dec);
cart3txt = view.findViewById(R.id.cart3txt);
quantity1 = Integer.parseInt(cart1txt.getText().toString());
quantity2 = Integer.parseInt(cart2txt.getText().toString());
quantity3 = Integer.parseInt(cart3txt.getText().toString());
buttonInitialization();
addingToCart();
return view;
}
private void addingToCart() {
btnCart1Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity1 <= 1){
btnCart1.setVisibility(View.VISIBLE);
btnCart1Dec.setVisibility(View.INVISIBLE);
btnCart1Inc.setVisibility(View.INVISIBLE);
cart1txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(1);
}else {
quantity1 = quantity1-1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
}
});
btnCart1Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity1 = quantity1+1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
});
btnCart2Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity2 <= 1){
btnCart2.setVisibility(View.VISIBLE);
btnCart2Dec.setVisibility(View.INVISIBLE);
btnCart2Inc.setVisibility(View.INVISIBLE);
cart2txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(2);
}else {
quantity2 = quantity2-1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
}
});
btnCart2Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity2 = quantity2+1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
});
btnCart3Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity3 <= 1){
btnCart3.setVisibility(View.VISIBLE);
btnCart3Dec.setVisibility(View.INVISIBLE);
btnCart3Inc.setVisibility(View.INVISIBLE);
cart3txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(3);
}else {
quantity3 = quantity3-1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
}
});
btnCart3Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity3 = quantity3+1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
});
}
private void buttonInitialization() {
btnCart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem1Price.getText().toString().trim();
itemDes = txtItem1Des.getText().toString().trim();
itemCount = cart1txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"1");
btnCart1.setVisibility(View.INVISIBLE);
btnCart1Dec.setVisibility(View.VISIBLE);
btnCart1Inc.setVisibility(View.VISIBLE);
cart1txt.setVisibility(View.VISIBLE);
}
});
btnCart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem2Price.getText().toString().trim();
itemDes = txtItem2Des.getText().toString().trim();
itemCount = cart2txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"2");
btnCart2.setVisibility(View.INVISIBLE);
btnCart2Dec.setVisibility(View.VISIBLE);
btnCart2Inc.setVisibility(View.VISIBLE);
cart2txt.setVisibility(View.VISIBLE);
}
});
btnCart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem3Price.getText().toString().trim();
itemDes = txtItem3Des.getText().toString().trim();
itemCount = cart3txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"3");
btnCart3.setVisibility(View.INVISIBLE);
btnCart3Dec.setVisibility(View.VISIBLE);
btnCart3Inc.setVisibility(View.VISIBLE);
cart3txt.setVisibility(View.VISIBLE);
}
});
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
addToCart = (AddToCart) context;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public interface AddToCart{
void cartCount(String item_img,String item_price,String item_desc,String item_count,String item_pos);
void removeItemFromCart(int removeItem);
void itemCount(String itemCount,String position);
}
}
Here in ProductFragment iam going to add values to text view. When i was coming from ReportFragment the view values are going to be cleared in ProductFragment.
I would consider doing that in two steps:
save fragment instance instead of re-creating a new one every time
private ProductFragment productFragment;
private ReportsFragment reportsFragment;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
if(productFragment == null)
productFragment = new ProductFragment();
loadFragment(productFragment);
break;
case R.id.nav_profile:
if(reportsFragment == null)
reportsFragment = new ReportsFragment();
loadFragment(reportsFragment);
break;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
referring to this question/answer, you should implement in your fragment both void onSaveInstanceState(final Bundle outState) and void onActivityCreated(Bundle savedInstanceState)
In that way you will surely keep the instance of your fragment instead of creating a new one every time (new MyFragment() will always re-create it). In addition, saving your views state in onSaveInstanceState and restoring it in your onActivityCreate, will allow you to keep your views/values.
I wrote that by hand without a compiler, so it might not be perfect.
let me know if you need further information.
Good luck
I am using this solution and it works for me.
You should see my detailed answer to a similar question. I hope it will solve your problem.
I have set up a BottomAppBar with a NavigationDrawer but I can't recover the item selected in this Drawer which is a fragment.
I followed many tutorials to set up this BottomAppBar but at no time did I see how to get the selection from the Drawer.
Here is how my Drawer is created:
public class MaintainerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintainer);
setUpBottomAppBar();
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.main_container, fragment);
transaction.commit();
}
private void setUpBottomAppBar() {
BottomAppBar bottomAppBar = findViewById(R.id.bottom_app_bar);
setSupportActionBar(bottomAppBar);
bottomAppBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialogFragment bottomSheetDialogFragment = BottomSheetNavigationMaintainerFragment.newInstance();
bottomSheetDialogFragment.show(getSupportFragmentManager(), "Bottom Sheet Dialog Fragment");
Bundle args = bottomSheetDialogFragment.getArguments();
}
});
bottomAppBar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
Finally, here is the code of my fragment:
public class BottomSheetNavigationMaintainerFragment extends BottomSheetDialogFragment {
public BottomSheetNavigationMaintainerFragment() {
// Required empty public constructor
}
public static BottomSheetNavigationMaintainerFragment newInstance() {
Bundle args = new Bundle();
BottomSheetNavigationMaintainerFragment fragment = new BottomSheetNavigationMaintainerFragment();
fragment.setArguments(args);
return fragment;
}
private BottomSheetBehavior.BottomSheetCallback mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
dismiss();
}
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) { }
};
#SuppressLint("RestrictedApi")
#Override
public void setupDialog(Dialog dialog, int style) {
super.setupDialog(dialog, style);
//Get the content View
View contentView = View.inflate(getContext(), R.layout.fragment_bottom_navigation_maintainer, null);
dialog.setContentView(contentView);
NavigationView navigationView = contentView.findViewById(R.id.navigation_view);
//implement navigation menu item click event
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.app_bar_assets:
break;
case R.id.app_bar_items:
break;
}
return false;
}
});
ImageView closeButton = contentView.findViewById(R.id.close_image_view);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//dismiss bottom sheet
dismiss();
}
});
//Set the coordinator layout behavior
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) ((View) contentView.getParent()).getLayoutParams();
CoordinatorLayout.Behavior behavior = params.getBehavior();
//Set callback
if (behavior instanceof BottomSheetBehavior) {
((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
}
}
}
I would therefore like to return the selected item in the onNavigationItemSelected method but I can't find a way to link this fragment to my activity in which it is created
How about introducing an interface like:
public interface OnItemSelectedListener {
void onItemSelected(int ItemId);
}
Make the MaintainerActivity implement this interface like this:
public class MaintainerActivity extends AppCompatActivity implements OnItemSelectedListener {
#Override
public void onItemSelected(int ItemId) {
//TODO - do something with this selected item...
}
}
And then in your BottomSheetNavigationMaintainerFragment do this:
private OnItemSelectedListener onItemSelectedListener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof OnItemSelectedListener){
onItemSelectedListener = (OnItemSelectedListener)context;
}
}
Then, when an item is selected:
//implement navigation menu item click event
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if(onItemSelectedListener != null){
onItemSelectedListener.onItemSelected(item.getItemId());
}
return false;
}
});
I am adding one fragment in activity. in which fragment I call bottomFragment on button click open a bottom sheet and on click of bottom bar text the toast print in the fragment.
Create Dialog class with a click event interface
public class AutoAppSelectrDialogFragment extends BottomSheetDialogFragment {
OnAutoAppSelectPickerListener mListener;
/**
* Factory method.
*
* #return A new instance of fragment ImagePickerDialogFragment.
*/
public static AutoAppSelectrDialogFragment newInstance(boolean showRemove) {
AutoAppSelectrDialogFragment fragment = new AutoAppSelectrDialogFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("showRemove", showRemove);
fragment.setArguments(bundle);
return fragment;
}
#SuppressLint("RestrictedApi")
#Override
public void setupDialog(final Dialog dialog, int style) {
super.setupDialog(dialog, style);
View contentView = View.inflate(getContext(), R.layout.bottom_sheet_auto_run, null);
ButterKnife.bind(this, contentView);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(contentView);
}
public void setListener(OnAutoAppSelectPickerListener listener) {
mListener = listener;
}
#OnClick(R.id.txt_1)
public void Click1() {
if (mListener != null)
mListener.onClick1();
dismiss();
}
#OnClick(R.id.txt_2)
public void Click2() {
if (mListener != null)
mListener.onClick2();
dismiss();
}
public interface OnAutoAppSelectPickerListener {
void onClick1();
void onClick2();
}
}
XML of dialogue Fragment layout bottom_sheet_auto_run
<TextView
android:id="#+id/txt_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:background="?actionBarItemBackground"
android:gravity="center"
android:padding="#dimen/dp_12"
android:textColor="#color/content_text_color"
android:textSize="#dimen/font_16_sp" />
<TextView
android:id="#+id/txt_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:background="?actionBarItemBackground"
android:gravity="center"
android:padding="#dimen/dp_12"
android:textColor="#color/content_text_color"
android:textSize="#dimen/font_16_sp" />
Open Bottom Sheet Dialogue on click of a button in fragment or activity like this and using a interface to implement an on click event of DialougeFragment layout
public class AutoSartInformation extends Fragment implements AutoAppSelectrDialogFragment.OnAutoAppSelectPickerListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
imgAutoStartApp = view.findViewById(R.id.img_auto_start_app);
imgAutoStartApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AutoAppSelectrDialogFragment imagePickerDialogFragment = AutoAppSelectrDialogFragment.newInstance(true);
imagePickerDialogFragment.setCancelable(false);
imagePickerDialogFragment.setListener(AutoSartInformation.this);
imagePickerDialogFragment.show(getActivity().getSupportFragmentManager(), imagePickerDialogFragment.getTag());
}
});
}
#Override
public void onClick1() {
Log.d("Click","1");
open Fragment on click of dialouge first text click
}
#Override
public void onClick2() {
Log.d("Click","2");
}
I have some slides with ViewPager that shows application help and I want to show it in DrawerLayout too.
this is HelpActivity.class:
public class HelpActivity extends Activity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
prefManager = new PrefManager(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.fragment_help);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_1,
R.layout.welcome_2,
R.layout.welcome_3,
R.layout.welcome_4,
R.layout.welcome_5,
R.layout.welcome_6,
R.layout.welcome_7};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(HelpActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(/*getString(R.string.start)*/ "Start");
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(/*getString(R.string.next)*/ "Next");
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
this is PrefManager.class:
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "stand up-welcome";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
and I use this code for defining it to drawerLayout:
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
with clicking on help in drawer, nothing shows. what should I do?
This is MainActivity.class:
ublic class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public Toolbar toolbar;
public NavigationView navigationView;
public ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new HomeFragment());
tx.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle= setupDrawerToggle();
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//navigation view
navigationView= (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(navigationView);
actionBarDrawerToggle.syncState();
// default item of navigation view
// navigationView.getMenu().getItem(0).setChecked(true);
navigationView.setCheckedItem(R.id.nav_item_home);
}//onCreate
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()==R.id.nav_item_setting){
startActivityForResult(new Intent(this, SettingActivity.class), 1002);
}
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
} return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState); // `onPostCreate` called when activity start-up is complete after `onStart()`
}
#Override
public void onBackPressed() {
MainActivity.this.finish();
}
}
in your xml:
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#drawable/background_drawer"
app:headerLayout="#layout/nav_header"
app:itemIconTint="#color/colorPrimary"
app:menu="#menu/menu_navigation" />
you have to add help options in your menu_navigation
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_item_help"
android:icon="#drawable/profile_icon"
android:title="Help" />
</group>
</menu>
Also in your MainActivity:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_setting:
Intent i = new Intent(MainActivity.this, SettingActivity.class);
startActivity(i);
break;
case R.id.nav_item_help:
Intent i = new Intent(MainActivity.this, HelpActivity.class);
startActivity(i);
break;
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
In your preference manager:
public void setFirstTimeLaunch(boolean isFirstTime) {
Editor editor = pref.edit();
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
difference between startactivity and startActivityForResult is:
1. startActvity():
startActivity() will start the activity you want to start without worrying about getting any result from new child activity started by startActivity to parent activity.
2. startAcitvityForResult():
startAcitvityForResult() starts another activity from your activity and it expect to get some data from newly started child activity by startAcitvityForResult() and return that to parent activity.
see this blog:https://malikshafique.wordpress.com/2012/06/14/android-startactivity-and-startactivityforresult/
I actually have an aplication with multiple activitys (on for each icon of my toolbar), also I would like to have the possibility to show the last fragment of these activitys from the stack if the user already open it before.
As you can see in my BaseActivity class below (which I extend for all my activitys), I already add fragments to the stack.
This is my class :
public class BaseActivity extends AppCompatActivity {
private final String TAG = "BaseActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public void setImageLoaderConfig(Context context) {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true)
.resetViewBeforeLoading(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
}
public void initToolBar() {
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.toolbar_layout);
Toolbar toolbar = (Toolbar) linearLayout.findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (toolbar != null) {
initToolbarOnClickListener();
}
}
private void initToolbarOnClickListener() {
(findViewById(R.id.toolbar_relativelayout_news)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ArticlesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_toilettes)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ToilettesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_practice)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(PratiquesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_diary)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(AgendaActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_forum)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ForumActivity.class);
}
});
}
public void updateToolbarIcons(Integer position) {
ImageView imageViewIcon;
Integer[] activeDrawableIds = {R.drawable.menu_actu_hover_320, R.drawable.menu_toilette_hover_320,
R.drawable.menu_pratiques_hover_320, R.drawable.menu_agenda_hover_320, R.drawable.menu_forum_hover_320};
Integer[] inactiveDrawableIds = {R.drawable.menu_actu_160, R.drawable.menu_toilette_320,
R.drawable.menu_pratiques_320, R.drawable.menu_agenda_320, R.drawable.menu_forum_320};
Integer[] imageviewIds = {R.id.toolbar_imageview_news, R.id.toolbar_imageview_bathroom,
R.id.toolbar_imageview_practice, R.id.toolbar_imageview_diary, R.id.toolbar_imageview_forum};
for (int i = 0; i < imageviewIds.length; i++) {
Log.d(TAG, i + " " + imageviewIds[i]);
imageViewIcon = (ImageView) findViewById(imageviewIds[i]);
if (i == position) {
imageViewIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), activeDrawableIds[i]));
} else {
imageViewIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), inactiveDrawableIds[i]));
}
}
if (AfamiciApp.isConnected()) {
ImageView imageViewUser = (ImageView) findViewById(R.id.toolbar_imageview_user);
imageViewUser.setVisibility(View.VISIBLE);
}
}
public void showActivity(Class activityClass) {
Intent intent = new Intent(this, activityClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
public void initIsConnected() {
if (AfamiciApp.getMail() != null && AfamiciApp.getPassword() != null) {
AfamiciApp.setIsConnected(true);
}
}
public void showConnexionFragment(Integer layoutId, Integer id) {
Bundle args = new Bundle();
args.putInt("id", id);
args.putInt("containerId", layoutId);
ConnexionFragment connexionFragment = new ConnexionFragment();
connexionFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, connexionFragment, null)
.addToBackStack(null)
.commit();
}
public void showCreationCommentaireFragment(Integer layoutId, Integer id, Boolean isFromConnection) {
if (isFromConnection) {
getSupportFragmentManager().popBackStack();
}
Bundle args = new Bundle();
args.putInt("id", id);
CommentaireFragment commentaireFragment = new CommentaireFragment();
commentaireFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, commentaireFragment, null)
.addToBackStack(null)
.commit();
}
public void showCreationCompteFragment(Integer layoutId, Integer id) {
Bundle args = new Bundle();
args.putInt("id", id);
CreationCompteFragment creationCompteFragment = new CreationCompteFragment();
creationCompteFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, creationCompteFragment, null)
.addToBackStack(null)
.commit();
}
}
Thanks in advance for your replys :)
You can get current fragment(last one added) in the FrameLayout using:
Fragment fragment = getSupportFragmentManager().findFragmentById(layoutId); //layoutId is id of FrameLayout
I have implemented the material design navigation drawer. However when selecting a new activity the navigation drawer doesn't close smoothly. (I have tried various solutions and suggestions here on SO, but nothing actually helps me)
So I am hoping someone has found a solution to this?
Here is my MainActivity.class:
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
private boolean doubleBackToExitPressedOnce;
private ProgressDialog pd = null;
private Object data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
// populate the navigation drawer
mNavigationDrawerFragment.setUserData("WELCOME", "", BitmapFactory.decodeResource(getResources(), R.drawable.ic_avatar));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FragmentHome();
break;
case 1:
fragment = new FragmentSecondActivity();
break;
case 2:
fragment = new FragmentThirdActivity();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please press BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
NavigationDrawerFragment:
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {
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 mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
#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;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
#Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}
public List<NavigationItem> getMenu() {
List<NavigationItem> items = new ArrayList<NavigationItem>();
items.add(new NavigationItem("Home", getResources().getDrawable(R.drawable.ic_home)));
items.add(new NavigationItem("Second Activity", getResources().getDrawable(R.drawable.ic_icon)));
items.add(new NavigationItem("Third Activity", getResources().getDrawable(R.drawable.ic_icon)));
return items;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#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().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
public void setUserData(String user, String email, Bitmap avatar) {
ImageView avatarContainer = (ImageView) mFragmentContainerView.findViewById(R.id.imgAvatar);
((TextView) mFragmentContainerView.findViewById(R.id.txtUserEmail)).setText(email);
((TextView) mFragmentContainerView.findViewById(R.id.txtUsername)).setText(user);
avatarContainer.setImageDrawable(new RoundImage(avatar));
}
public View getGoogleDrawer() {
return mFragmentContainerView.findViewById(R.id.googleDrawer);
}
public static class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
}
What can I do to make closing the navigation drawer close smoothly? At the moment it closes halfway then stops for a second then closes and the new activity is shown.
add the below method before calling another class on navigation drawer item click i.e. in onnavigationdrawerselected method
mNavigationDrawerFragment.closeDrawers();
This will close the navigation drawer..
close your drawer first.
after 200ms, open your new activity
USE A THREAD TO CLOSE THE DRAWER THAT CAN IMPROVE SOME CASES
new Handler().post(new Runnable() {
#Override
public void run() {
drawerLayout.closeDrawers();
}
});