On resume each fragment in bottom navigation layout lags - android

I am using Bottom Navigation Layout to show 5 fragments but the problem is after every onResume is called each fragment start lagging more and more.
This is my main activity with contain bottom navigation
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_home:
if (!selectedFragment.equalsIgnoreCase(Consts.MasterHomeFragment)) {
openMasterHomeFragment();
}
break;
case R.id.menu_wallet:
if (!isSessionActive()) {
showLoginBottomDialog();
return false;
} else {
if (!selectedFragment.equalsIgnoreCase(Consts.WalletFragment))
openWalletFragment();
}
break;
case R.id.menu_portfolio:
if (!isSessionActive()) {
showLoginBottomDialog();
return false;
} else {
if (!selectedFragment.equalsIgnoreCase(Consts.PortfolioFragment))
openPortfolioFragment();
}
break;
on each method i do
public void openPortfolioFragment() {
eventTracker.track(EventTracker.HOME_PORTFOLIO_NAV_CLICKED);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
PortfolioFragment portfolioFragment = new PortfolioFragment();
transaction.replace(R.id.activity_home_main_frame, portfolioFragment);
transaction.commit();
selectedFragment = Consts.PortfolioFragment;
}
public void openProfileFragment() {
eventTracker.track(EventTracker.HOME_ACCOUNT_NAV_CLICKED);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
ProfileFragment profileFragment = new ProfileFragment();
transaction.replace(R.id.activity_home_main_frame, profileFragment);
transaction.commit();
selectedFragment = Consts.ProfileFragment;
}
and oneach fragment onresume calling api
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_wallet, container, false);
unbinder = ButterKnife.bind(this, view);
initViewPager(view);
return view;
}
#Override
public void onResume() {
super.onResume();
loadDataFromApi();
}
and rendering data
#Override
public void onDataLoaded(MasterHomeResponse response) {
if (getActivity() != null && isAdded()) {
masterHomeResponse = response;
hideRefreshing();
initPortfolio(response);
initInbox(response.getInbox());
initAssets(response);
initTutorial(response);
initFeeds(response);
showBottomMoreFloatingButton();
boolean dismissIntro = sharedPreferenceHelper.getSamplePreference().getShowCase();
showGuideView(response, dismissIntro);
}
}
when ever i go to background and come back to application every fragment start lagging on scrolling

I was searching solution for this issue i have got this link Android Facebook SDK lowers app performance me also using facebook sdk for login purpose so making autologging value to false my issue resolved.

Related

Performclick does not function with android fragment

I have a problem with android studio. I use a fragment with a bottomNavigationView. It works fine if you click on the bottomNavigation. But if you simulate a click on the bottomNavigation it works for the first time and at the second time if you simulate the performclick again, it does not work.
I used also view.callOnClick(); and for the fragment add and remove fragment, but both do not function for my problem. I really appreciate it, if anyone can solve my problem.
Here is the Code:
`
public class ProfileFragment extends Fragment {
private Button send_order_button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstaceState) {
return inflater.inflate(R.layout.profile_fragment, container,false);
}
#Override
public void onStart() {
send_order_button = (Button) getView().findViewById(R.id.auftrag_abschicken);
}
send_order_button.setOnClickListener(new View.OnClickListener() {
ProfilActivity pa = new ProfilActivity();
pa.changeFragment();
getActivity().finishActivity(ProfilActivity.class.hashCode());
}
}`
`
public class ProfilActivity extends AppCompatActivity {
public ProfilActivity() {}
public static Fragment selectedFragment = null;
public static BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
View view = bottomNavigationView.findViewById(R.id.nav_chat);
view.performClick();
}
public void changeFragment() {
// bottomNavigationView.setSelectedItemId(R.id.nav_store);
View view = bottomNavigationView.findViewById(R.id.nav_store);
view.performClick();
}
public BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_user :
selectedFragment = new ProfileFragment();
break;
case R.id.nav_chat :
selectedFragment = new MailFragment();
break;
case R.id.nav_store:
selectedFragment = new ShopFragment();
break;
}
try {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment, "fragment").commitAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
};
return true;
}
};
}`
It looks like you're trying to set the default selected item in the BottomNavigationView. Why not just use bottomNavigationView.setSelectedItemId(R.id.nav_store); ?

Android selecting element from navigation bar freezes load

I have a bottom navigation bar with multiple elements that send me to different fragments .
bottomNavigationView.setOnNavigationItemSelectedListener
(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_pokemon_description:
selectedFragment = PokemonDescriptionFragment.newInstance(MainActivity.getSelectedPokemon().get_id());
break;
case R.id.navigation_pokemon_evolutions:
selectedFragment = PokemonEvolutionsFragment.newInstance();
break;
case R.id.navigation_pokemon_moves:
selectedFragment = PokemonMovesFragment.newInstance();
break;
case R.id.navigation_pokemon_breeding:
selectedFragment = PokemonBreedingTrainingFragment.newInstance();
break;
case R.id.navigation_pokemon_location:
selectedFragment = PokemonLocationFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.commit();
return true;
}
});
All the fragments works fine except the Moves fragment , when I press it , it costs around 3 seconds to load the data and display the fragment .
I would like to show the fragment first and then , load the moves and show a progress bar or something like that while the data is loading .
This is my fragment :
public class PokemonMovesFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseAccess = DatabaseAccess.getInstance(getContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pokemon_moves, container, false);
this.view=view;
initalizeAllComponents();
initializePokemonData();
initializePostDataPopulationComponents();
getActivity().setTitle(getResources().getText(R.string.moves)+ " (" +selectedPokemon.getName() + ")");
return view;
}
//The rest of the methods
Simply move all your logic inside onViewCreated, then show Progressbar before the logic and hide Progressbar after the logic
#Override
public View onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState)
progressBar.visibility = View.VISIBLE; // Show Progress bar here
initalizeAllComponents();
initializePokemonData();
initializePostDataPopulationComponents();
getActivity().setTitle(getResources().getText(R.string.moves)+ " (" +selectedPokemon.getName() + ")");
progressBar.visibility = View.INVISIBLE; // Hide Progress bar here
}

Pass HashMap of fragments to bundle

I'm using HashMap of fragment's backstack. To save backstack and current fragment I use the code below:
public class MainActivity extends AppCompatActivity {
private HashMap<String, Stack<Fragment>> mStacks;
public static final String TAB_PROFILE = "tab_profile";
public static final String TAB_DASHBOARD = "tab_dashboard";
public static final String TAB_CHATS = "tab_chats";
public static final String TAB_SETTINGS = "tab_settings";
private String mCurrentTab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupViews();
if (savedInstanceState != null) {
mCurrentTab = savedInstanceState.getString("currentTab");
mStacks = (HashMap<String, Stack<Fragment>>) savedInstanceState.getSerializable("stacks");
} else
selectedTab(TAB_DASHBOARD);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("stacks", mStacks);
outState.putString("currentTab", mCurrentTab);
}
private void setupViews() {
mStacks = new HashMap<>();
mStacks.put(TAB_PROFILE, new Stack<>());
mStacks.put(TAB_DASHBOARD, new Stack<>());
mStacks.put(TAB_CHATS, new Stack<>());
mStacks.put(TAB_SETTINGS, new Stack<>());
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
bottomNavigationView.setSelectedItemId(R.id.action_dashboard);
BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
switch (item.getItemId()) {
case R.id.action_profile:
selectedTab(TAB_PROFILE);
return true;
case R.id.action_dashboard:
selectedTab(TAB_DASHBOARD);
return true;
case R.id.action_chats:
selectedTab(TAB_CHATS);
return true;
case R.id.action_settings:
selectedTab(TAB_SETTINGS);
return true;
}
return true;
});
bottomNavigationView.setOnNavigationItemReselectedListener(item -> {
if (mStacks.get(mCurrentTab).size() != 1) {
mStacks.get(mCurrentTab).clear();
switch (item.getItemId()) {
case R.id.action_profile:
selectedTab(TAB_PROFILE);
break;
case R.id.action_dashboard:
selectedTab(TAB_DASHBOARD);
break;
case R.id.action_chats:
selectedTab(TAB_CHATS);
break;
case R.id.action_settings:
selectedTab(TAB_SETTINGS);
break;
}
}
});
}
private void selectedTab(String tabId) {
mCurrentTab = tabId;
if(mStacks.get(tabId).size() == 0){
if(tabId.equals(TAB_PROFILE)){
Fragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putSerializable("user", Globals.getCurrentUser());
fragment.setArguments(args);
pushFragments(tabId, fragment,true);
} else if(tabId.equals(TAB_DASHBOARD)){
pushFragments(tabId, new DashboardFragment(),true);
}else if(tabId.equals(TAB_CHATS)){
pushFragments(tabId, new GroupsFragment(),true);
}else if(tabId.equals(TAB_SETTINGS)){
pushFragments(tabId, new SettingsFragment(),true);
}
}else {
pushFragments(tabId, mStacks.get(tabId).lastElement(),false);
}
}
public void pushFragments(String tag, Fragment fragment, boolean shouldAdd){
if(shouldAdd)
mStacks.get(tag).push(fragment);
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content, fragment);
ft.commit();
}
public void popFragments(){
Fragment fragment = mStacks.get(mCurrentTab).elementAt(mStacks.get(mCurrentTab).size() - 2);
mStacks.get(mCurrentTab).pop();
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content, fragment);
ft.commit();
}
#Override
public void onBackPressed() {
if(mStacks.get(mCurrentTab).size() == 1){
finish();
return;
}
popFragments();
}
}
Set new fragments using
((MainActivity)context).pushFragments(MainActivity.TAB_CHATS, fragment,true);
Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#color/background_material_light"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation"/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="#color/waPrimary"
app:itemIconTint="#color/white"
app:itemTextColor="#color/white"
app:menu="#menu/menu_bottom_navigation" />
Everything works fine on screen rotation, but application crashes with exception on application hide.
java.lang.RuntimeException: Parcel: unable to marshal value %FragmentName%{c985244 #2 id=0x7f090051}
As I read, it happens when one of the objects I'm trying to pass is not Parceable, but have no idea how to fix this. Any thoughts?
UPD
After I made all of my fragments Serializable, new exception throws
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = %FragmentName%)
...
Caused by: java.io.NotSerializableException: android.support.v7.widget.RecyclerView
UPD2
Seems like a found a solution - transient property. Now I'm trying to make all non-serializeable objects transient.
UPD3
It helped, but I don't know is it efficient enough.
Here's my suggestion:
Your activity maintains a reference to the four fragments it wants for the bottom navigation toggling.
On toggling bottom navigation, you replace the current fragment in the activity fragment manager.
While on a given fragment, as you interact with the UI, you push things on to the fragment child fragment manager.
This way, each fragment maintains its own backstack automatically, you don't have to save any state, and it all Just Works™.
Some sample code that might help.
public class MainActivity extends AppCompatActivity {
private Fragment mProfileFragment;
private Fragment mDashboardFragment;
private Fragment mChatsFragment;
private Fragment mSettingsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
// Init fragments
}
else {
// Find last active fragments in fragment manager
}
setupViews();
}
private void setupViews() {
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setSelectedItemId(R.id.action_dashboard);
BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
Fragment fragment;
switch (item.getItemId()) {
case R.id.action_profile:
fragment = mProfileFragment;
break;
case R.id.action_dashboard:
fragment = mDashboardFragment;
break;
case R.id.action_chats:
fragment = mChatsFragment;
break;
case R.id.action_settings:
fragment = mSettingsFragment;
break;
}
// Replace the currently active fragment which will be
// managing its own backstack
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frament_container, fragment)
.commit();
});
}
}
And one of your fragments would push stuff on its own stack like this:
public class ProfileFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.id.fragment_layout, container, false);
Button button = view.findViewById(R.id.some_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment someFragmentToPush = new SomeFragmentToPush();
// Use the child fragment manager to keep UI
// local to this fragment instance, adding to backstack
// for automatic popping on pressing back
getChildFragmentManager().beginTransaction()
.add(R.id.fragment_layout, someFragmentToPush)
.addToBackStack(null)
.commit();
}
});
return view;
}
}
Hope that helps!

How to implement proper back navigation for the Android BottomNavigation

I spent my whole day now looking for an answer and didn't found any solution that suited this question.
I am looking for a way to create a BottomNavigation usage similar to the one of the Instagram or PlayKiosk app. Fragments should be added to the back stack only once. When pressing the back button I'd expect the app to jump back to the last Fragment that was visited and the button of the BottomNavigation to fit that Fragment.
Currently I use the following code:
//BottomNavigationListener
private BottomNavigationView.OnNavigationItemSelectedListener buttonNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
switch (item.getItemId()) {
case R.id.navigation_game:
currentFragment = GameFragment.newInstance();
fragmentManager.beginTransaction()
.addToBackStack(TAG_FRAGMENT_GAME)
.replace(R.id.content_frame, currentFragment, TAG_FRAGMENT_GAME)
.commit();
break;
case R.id.navigation_tournament:
currentFragment = TournamentFragment.newInstance();
fragmentManager.beginTransaction()
.addToBackStack(TAG_FRAGMENT_TOURNAMENT)
.replace(R.id.content_frame, currentFragment, TAG_FRAGMENT_TOURNAMENT)
.commit();
break;
case R.id.navigation_history:
break;
}
return true;
}
};
But this leads to the problem that I could press the button of my BottomNavigation a couple of times and for each of this clicks a new Fragment would be instantiated. Also the BottomNavigation buttons are not set according to the Fragments.
I found this answer but it didn't work out Prevent The Same Fragment From Stacking More Than Once ( addToBackStack)
You can use following structure to have the same working logic of Instagram.
First create a custom limited unique queue class. It only holds last N items, where N is the limit number (or maximum item count) passed to its constructor. Moreover, this type of queue keeps only one instance of a class. If an instance of class A is already in the queue and another instance of class A is to be added to the queue, the former instance is removed first and then the new object is inserted.
public class LimitedUniqueQueue<E> extends LinkedList<E> {
private int limit;
public LimitedUniqueQueue(int limit) {
this.limit = limit;
}
#Override
public boolean add(E o) {
// For uniqueness
for (int i = 0; i < super.size(); i++) {
E item = super.get(i);
if (item.getClass() == o.getClass()) {
super.remove(i);
break;
}
}
boolean added = super.add(o);
// For size limit
while (added && size() > limit) {
super.remove();
}
return added;
}
}
Then update your Activity as follows:
public class MainActivity extends AppCompatActivity {
private BottomNavigationView navigation;
private LimitedUniqueQueue<Fragment> queue;
...
private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
Fragment gameFragment;
Fragment tournamentFragment;
Fragment profileFragment;
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
switch (item.getItemId()) {
case R.id.navigation_game:
if (gameFragment == null) {
gameFragment = new GameFragment();
}
transaction.replace(R.id.content, gameFragment).commit();
queue.add(gameFragment);
return true;
case R.id.navigation_tournament:
if (tournamentFragment == null) {
tournamentFragment = new TournamentFragment();
}
transaction.replace(R.id.content, tournamentFragment).commit();
queue.add(tournamentFragment);
return true;
case R.id.navigation_profile:
if (profileFragment == null) {
profileFragment = new ProfileFragment();
}
transaction.replace(R.id.content, profileFragment).commit();
queue.add(profileFragment);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigation = (BottomNavigationView) findViewById(R.id.navigation);
queue = new LimitedUniqueQueue<>(navigation.getMenu().size());
navigation.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener);
navigation.setSelectedItemId(R.id.navigation_game);
...
}
#Override
public void onBackPressed() {
if (queue.size() > 1) {
queue.removeLast();
Fragment previousFragment = queue.getLast();
if (previousFragment instanceof GameFragment) {
navigation.setSelectedItemId(R.id.navigation_game);
} else if (previousFragment instanceof TournamentFragment) {
navigation.setSelectedItemId(R.id.navigation_tournament);
} else if (previousFragment instanceof ProfileFragment) {
navigation.setSelectedItemId(R.id.navigation_profile);
}
} else {
super.onBackPressed();
}
}
...
}

How backPress works in fragment?

I am trying to use backpress on fragments. I am not able to fix it. Here is my code below.
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
if (position!=3){
pos = position;
}
switch (position) {
case 0:
fragment = new Profile();
break;
case 1:
fragment = new Products();
break;
case 2:
fragment = new Help();
break;
case 3:
DialogLogout(DrawerFragment.this, getString(R.string.logout), getString(R.string.cofirm_logout));
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment)
.commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(pos, true);
mDrawerList.setSelection(pos);
setTitle(navMenuTitles[pos]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
On Product Fragment I have list in which I again use to call another fragment.
listCards.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new Transactions();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
// .replace(R.id.frame_container, fragment)
.remove(Products.this)
.add(R.id.frame_container, fragment) //replace(R.id.frame_container, fragment)
.addToBackStack(null)
.commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
});
return rootView;
}
BackPress functionality on DrawerFragmentActivity is like below:
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
int count = fragmentManager.getBackStackEntryCount();
if (count > 0) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
super.onBackPressed();
}
}
Functionality would be like, DrawerFragmentActivity(Profile page by default)->Product->Transactions. Drawer Icon would be visible on Transactions screen as well, user can click my cards screen again while on transaction screen using drawer.
When user click on product it will again open transactions page, It's working fine. Now what happening is, when we click back on transaction it is coming on Product page, but When I again click on Product list screen(Frame) is overlapping with ProductsList and Transactions screen.
I am sorry if I it's confusing, Please ask if you don't understand. I can explain.
Thanks.
Fragment back press working code
public class ChiefFragment extends Fragment {
View view;
// public OnBackPressedListener onBackPressedListener;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle args) {
view = inflater.inflate(R.layout.activity_chief, container, false);
getActivity().getActionBar().hide();
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.i(getTag(), "keyCode: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().getActionBar().show();
Log.i(getTag(), "onKey Back listener is working!!!");
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
// String cameback="CameBack";
Intent i = new Intent(getActivity(), home.class);
// i.putExtra("Comingback", cameback);
startActivity(i);
return true;
} else {
return false;
}
}
});
return view;
}
}
Use below code for back pressed in fragment.
public class DashBoard extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dashboard, container, false);
rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
rootView.setOnKeyListener(new View.OnKeyListener(){
#Override
public boolean onKey(View v, int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().finish(); }
return true;
}
return false;
}
});
}
this code help you to implement your backpreesed in fragment.
I would recommend you to implement an interface to manage backstack. Here is a good blog post which would help you understand this process

Categories

Resources