The Main Activity having bottom navigation and contains 5 fragments in it. Each fragments having multiple fragment inside. how to handle the onbackpressed in it.
Homepage.java
public class Homepage extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.home:
selectedFragment = Fragment_home.newInstance();
break;
case R.id.eventsfeed:
selectedFragment = Fragment_eventsfeed.newInstance();
break;
case R.id.events:
selectedFragment = Fragment_events.newInstance();
break;
case R.id.messages:
selectedFragment = Fragment_messages.newInstance();
break;
case R.id.settings:
selectedFragment = Fragment_settings.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content, selectedFragment);
transaction.commit();
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
Fragment fragmentnewview = new Fragment_home();
FragmentManager frMan = getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
BottomNavigationViewHelper.disableShiftMode(navigation);
}}
Fragment_home.java
public class Fragment_home extends Fragment {
public static Fragment_home newInstance(){
Fragment_home fragment=new Fragment_home();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.fragment_home, container, false);
CardView card=(CardView)view.findViewById(R.id.next_page_home_card);
card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Event_details();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
return view;
}
}
Inside that Fragment_home.java i have a card view when it clicked it goes to next fragment Event_Details.java
Event_Details.java
public class Event_details extends Fragment {
Button add_comments;
ImageButton back;
public static Event_details newInstance(){
Event_details fragment=new Event_details();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.event_details, container, false);
add_comments=(Button)view.findViewById(R.id.add_comment);
back=(ImageButton)view.findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Fragment_home();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
add_comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Comments();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
return view;
}
}
i have a button in Event_Details.java when clicked that it calls another fragment Comments.java
Comments.java
public class Comments extends Fragment {
ImageButton back;
public static Comments newInstance(){
Comments fragment=new Comments();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.add_your_comments, container, false);
back=(ImageButton)view.findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Event_details();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
return view;
}
}
back.setOnClickListener is the image button to go back but i can't implement in the hardware back button.
You need to #Override your activity onBackPressed() method !!!
There are many good information and answers about your question ! if you want to become good programmer you need good research skills!!! :))
Try to research and solve the problem yourself . Write some code, and after all of it if you still can't resolve your problem i'll give you code for copy and paste :)
When you load a fragment, use addToBackStack(null) on the FragmentTransaction. If you do that, the back button will reverse the transaction.
#Override onBackPressed()
method as #L.Petrosyan told,
insideonBackPressed()get the current position of your viewpager usingviewPager.getCurrentItem();
it will return you anint` value. use that value to manage your code.
Related
I am trying to implement tablayout in a fragment which is already part of BottomNavigationView, I am facing a problem while navigating through navigation bar, There is a recycler view in a fragment which is the part of tablayout, now when I navigate between fragments via BottomNavigation the recyclerview becomes empty, and there is nothing in the logcat.
MainActivity
public class MainActivity extends AppCompatActivity {
private BottomNavigationView navigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
initComponent();
loadFragment(new HomeFragment());
}
private void initComponent() {
navigation = findViewById(R.id.navigation);
BottomNavigationViewHelper.disableShiftMode(navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// ViewAnimation.fadeOutIn(fragme);
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.home_main:
fragment = new HomeFragment();
break;
case R.id.search:
fragment = new SearchFragment();
break;
case R.id.notifications:
fragment = new NotificationsFragment();
break;
case R.id.favourite:
fragment = new FavouriteFragment();
break;
}
return loadFragment(fragment);
}
});
findViewById(R.id.bt_menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
HomeFragment
public class HomeFragment extends Fragment {
private ViewPager view_pager;
private TabLayout tab_layout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, null);
view_pager = view.findViewById(R.id.view_pager);
setupViewPager(view_pager);
tab_layout = view.findViewById(R.id.tab_layout);
tab_layout.setupWithViewPager(view_pager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new PresetsFragment(), "Presets");
/* adapter.addFragment(new PresetsFragment(), "Tutorials");
adapter.addFragment(new PresetsFragment(), "Categories");*/
viewPager.setAdapter(adapter);
}
#Override
public void onDestroy() {
super.onDestroy();
tab_layout = null;
view_pager = null;
}
PresetsFragment
public class PresetsFragment extends Fragment {
RecyclerView recyclerView;
PresetsAdapter presetsAdapter;
String[] presetList = {"s", "s", "d", "d"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_presets, container, false);
recyclerView = view.findViewById(R.id.presetsRecyclerView);
presetsAdapter = new PresetsAdapter(presetList, getActivity());
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(presetsAdapter);
//presetsAdapter.notifyDataSetChanged();
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
I have spent so many hours to figure it out but still unable to get it..
from your loadFragment method you are using FrameLayout and replacing fragment on BottomNavigation selection when you do so you are creating a new fragment every time if you used a ViewPager it will work fine with you
I have a problem with my Bottom bar in android. when i click on the bottom menu options it goes blank. Please help me out to fine what is the basic problem. Where is am I wrong.
It shows no error or exception in logcat.
Here is my code
public class BottomBarActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_bar);
final BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_library:
FragmentLibrary fragmentLibrary = new FragmentLibrary();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frame_layout1, fragmentLibrary);
fragmentTransaction.commit();
Toast.makeText(BottomBarActivity.this, "Library", Toast.LENGTH_SHORT).show();
break;
case R.id.action_notification:
//002
Fragment selectedFragmentNotification = FragmentNotification.newInstance();
FragmentTransaction fragmentTransactionNotification = getSupportFragmentManager().beginTransaction();
fragmentTransactionNotification.replace(R.id.frame_layout1, selectedFragmentNotification);
fragmentTransactionNotification.commit();
Toast.makeText(BottomBarActivity.this, "Notifications", Toast.LENGTH_SHORT).show();
break;
case R.id.action_more:
Fragment selectedFragmentMore = FragmentMore.newInstance();
FragmentTransaction fragmentTransactionMore = getSupportFragmentManager().beginTransaction();
fragmentTransactionMore.replace(R.id.frame_layout1, selectedFragmentMore);
fragmentTransactionMore.commit();
Toast.makeText(BottomBarActivity.this, "More", Toast.LENGTH_SHORT).show();
break;
case R.id.action_discovered:
Fragment selectedFragmentMain = FragmentMain.newInstance();
FragmentTransaction fragmentTransactionMain = getSupportFragmentManager().beginTransaction();
fragmentTransactionMain.replace(R.id.frame_layout1, selectedFragmentMain);
fragmentTransactionMain.commit();
Toast.makeText(BottomBarActivity.this, "Discover", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
//Manually displaying the first fragment
Fragment selectedFragment = FragmentMain.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout1, selectedFragment);
fragmentTransaction.commit();
}
}
Here is the Fragment Class Code.
This fragment is called when I click one of the menu item.
public class FragmentLibrary extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
private PagerSlidingTabStrip tabs_L;
private ViewPager pager_L;
public FragmentLibrary() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_library, container, false);
pager_L = (ViewPager) view.findViewById(R.id.pagerL);
pager_L.setAdapter(new MyAdapterLibrary(getFragmentManager()));
tabs_L = (PagerSlidingTabStrip) view.findViewById(R.id.tabsL);
tabs_L.setViewPager(pager_L);
return view;
}
// ADAPTER CLASS
public class MyAdapterLibrary extends FragmentPagerAdapter {
private String[] titles = {
getString(R.string.tab_title_current_reading),
getString(R.string.tab_title_reading_lists),
getString(R.string.tab_title_history)
};
public MyAdapterLibrary(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentCurrentReading.newInstance(position);
case 1:
return FragmentReadingLists.newInstance(position);
case 2:
return FragmentHistory.newInstance(position);
}
return null;
}
#Override
public int getCount() {
return titles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
I am working in an application where i am calling Fragment2 from Fragment1, when I am pressing default back button in Fragment2 it is taking me to Fragment1 but when I am pressing any other button and calling getActivity.finish() it is closing my Activity.
I have added the code below:
MainActivity.java
public class MainActivity extends AppCompatActivity {
AHBottomNavigation bottomNavigation;
Fragment selectedFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigation = (AHBottomNavigation) findViewById(R.id.navigation);
AHBottomNavigationItem item1 = new AHBottomNavigationItem(R.string.home, R.drawable.home, R.color.colorAccent);
AHBottomNavigationItem item2 = new AHBottomNavigationItem(R.string.menu, R.drawable.menu, R.color.colorAccent);
AHBottomNavigationItem item3 = new AHBottomNavigationItem(R.string.cart, R.drawable.cart, R.color.colorAccent);
AHBottomNavigationItem item4 = new AHBottomNavigationItem(R.string.orders, R.drawable.orders, R.color.colorAccent);
AHBottomNavigationItem item5 = new AHBottomNavigationItem(R.string.settings, R.drawable.setting, R.color.colorAccent);
bottomNavigation.addItem(item1);
bottomNavigation.addItem(item2);
bottomNavigation.addItem(item3);
bottomNavigation.addItem(item4);
bottomNavigation.addItem(item5);
bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
bottomNavigation.setAccentColor(Color.parseColor("#571e19"));
selectedFragment = ItemHomeFragment.newInstance(bottomNavigation);
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
if (position == 0) {
selectedFragment = ItemHomeFragment.newInstance(bottomNavigation);
} else if (position == 4) {
selectedFragment = Fragment1 (bottomNavigation);
}
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout,selectedFragment);
fragmentTransaction.commit();
return true;
}
});
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, ItemHomeFragment.newInstance(bottomNavigation));
fragmentTransaction.commit();
}
public void setNotification(){
bottomNavigation.setNotification("1", 1);
}
}
Fragment1.java
public class Fragment1 extends Fragment {
public static AHBottomNavigation bottomNavigation1;
TextView txtLogout,txtMyProfile,txtTermsCondition,txtRate;
public int LANGUAGE_REQUEST_CODE = 113;
private SharedPreferences prefs ;
Boolean languageBoolean = true;
MyApplication myApplication;
private UIView uiView = UIView.getInstance();
ProgressDialog pDialog;
static int index;
public static ItemSettingsFragment newInstance(AHBottomNavigation bottomNavigation) {
ItemSettingsFragment fragment = new ItemSettingsFragment();
bottomNavigation1 = bottomNavigation;
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
showNotificationCounter(32);
View view = inflater.inflate(R.layout.fragment_settings, container, false);
TextView txtLanguage = (TextView) view.findViewById(R.id.txtLanguage);
txtLanguage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), LanguageActivity.class);
startActivity(intent);
}
});
txtMyProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment fragment2 = new ProfileFragment();
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return view;
}
Fragment2.java
public class Fragment2 extends Fragment{
public Fragment2() { }
public static Fragment newInstance() {
Fragment2 profileFragment = new Fragment2();
return profileFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.language, container, false);
TextView fragment2 = (TextView) view.findViewById(R.id.txtLanguage);
fragment2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
return view;
}
}
Don't
getActivity.finish()
finish() clear the Activity.
Do
popBackStack();
Example
FragmentManager fmOBJ= getFragmentManager();
fmOBJ.popBackStack();
In this function on click of nav_manage I want to open ViewTasks that extends ListFragment. Can someone please suggest some code example?
This is a function in my MainActivity.
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId)
{
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_send:
fragment = new Invitation();
break;
case R.id.nav_camera:
fragment=new Home();
break;
case R.id.nav_manage:
fragment=new ViewTasks();
break;
default:
Toast.makeText(MainActivity2.this,"Choose Something",Toast.LENGTH_LONG).show();
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
My ViewTasks class:
public class ViewTasks extends ListFragment {
private Button addButton;
private TaskManagerApplication app;
private TaskListAdapter adapter;
private Button removeButton;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.home_fragment, container, false);
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Task Scheduler");
app = (TaskManagerApplication)getActivity().getApplication();
adapter = new TaskListAdapter(this.getActivity(), app.getCurrentTasks());
setListAdapter(adapter);
setUpViews();
}
#Override
public void onResume() {
super.onResume();
adapter.forceReload();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
adapter.toggleTaskCompleteAtPosition(position);
Task t = adapter.getItem(position);
app.saveTask(t);
}
protected void removeCompletedTasks() {
Long[] ids = adapter.removeCompletedTasks();
app.deleteTasks(ids);
}
private void setUpViews() {
addButton = (Button)getView().findViewById(R.id.add_button);
removeButton = (Button)getView().findViewById(R.id.remove_button);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new AddTaskActivity())
.commit();
}
});
removeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
removeCompletedTasks();
}
});
}
}
I want this function to open the ViewTasks fragment which has listview of tasks scheduled.
When I follow the same pattern as my above case it shows this error:
Incompatible types:
Required: android.app.Fragment
Found: com.happy.taskmanager.ViewTasks
Here is my code
I need to go from A->B->C and onBackPressed() from B and C should go to A
while pressing back it goes to B and then to C , It seems to me that transaction.addToBackStack(null); not using as needed
public class TestfragmentActivity extends FragmentActivity{
private FrameLayout layout;
private String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_fragment);
layout = (FrameLayout) findViewById(R.id.container);
A fragment = new A();
doFragmentTransaction(fragment, false);
}
private void doFragmentTransaction(Fragment fragment, boolean addToBackstack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, fragment);
if (addToBackstack)
transaction.addToBackStack(TAG);
transaction.commit();
}
///////////////
public class A extends Fragment {
private Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.test_fragment1, null);
button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
B fragment = new B();
doFragmentTransaction(fragment, true);
}
});
return view;
}
private void doFragmentTransaction(Fragment fragment, boolean addToBackstack) {
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
if (addToBackstack) {
transaction.addToBackStack(null);
}
transaction.commit();
}
//////////////////////
public class B extends Fragment {
private Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.test_fragment2, null);
button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
C fragment = new C();
doFragmentTransaction(fragment, false);
}
});
return view;
}
private void doFragmentTransaction(Fragment fragment, boolean addToBackstack) {
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
if (addToBackstack)
transaction.addToBackStack(null);
transaction.commit();
}
}
}
in fragment B and C,
#Override
public void onBackPressed() {
}
in the function, replace the Container with Fragment A.