Adding and removing fragment with same button from framelayout - android

I am new to android working first time on fragment.I am creating an app in which I want to add a fragment on frame layout.I am able to do this but now what I want is to remove the same fragment which i added by that same button click I tried but couldn't. here is my code.
public void onClick(View v) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
if(v.getId() == R.id.clickme){
if(getSupportFragmentManager().findFragmentById(R.layout.fragment_one) != null){
// getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentById(R.layout.fragment_one)).commit();
Fragment fragment = new FragmenOne();
fragmentManager.beginTransaction().remove(fragment).commit();
}else{
Fragment fragment = new FragmenOne();
// android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.my_frame, fragment)
.commit();
}
}
}

You need to do in this manner
Fragment f = fragmentManager.findFragmentById(R.id.my_frame);
if(f instanceof FragmenOne) {
FragmenOne oneFragment = (FragmenOne) f;
FragmentTransaction trans = manager.beginTransaction();
trans.remove(oneFragment);
trans.commit();
fragmentManager.popBackStack();
}else{
Fragment fragment = new FragmenOne();
fragmentManager.beginTransaction()
.replace(R.id.my_frame, fragment)
.commit();
}

Related

Checking if a view exists before loading a fragment

I would like to see if a view exists before loading a fragment. In my method that loads the fragment i have below :
public void loadFragment(Fragment fragment){
FragmentManager fragmentManager = Objects.requireNonNull(getActivity()).getSupportFragmentManager();
// Begin Fragment transaction.
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();// Replace the layout holder with the required Fragment object.
fragmentTransaction.replace(R.id.outbound_dashboard_hourly_queued, fragment);
// Commit the Fragment replace action.
fragmentTransaction.commit();
}
What i want is to check if R.id.outbound_dashboard_hourly_queued exists before loading
How do i proceed ?
just do findViewById(R.id.outbound_dashboard_hourly_queued) and then load the fragment if the view is not Null keep a if check.
public void loadFragment(Fragment fragment){
FragmentManager fragmentManager = Objects.requireNonNull(getActivity()).getSupportFragmentManager();
// Begin Fragment transaction.
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();// Replace the layout holder with the required Fragment object.
View yourView= findViewById(R.id.outbound_dashboard_hourly_queued);
if(yourView!=null){
fragmentTransaction.replace(R.id.outbound_dashboard_hourly_queued, fragment);
// Commit the Fragment replace action.
fragmentTransaction.commit();
}
}
try this
Check is Fragmnet added or not
if (getCurrentFragment() instanceof YourFragment)
Add Framgnet
replaceFragment(new HomeFragment(), "YourFragment");
Methods
private void replaceFragment(Fragment fragment, String tag)
{
Fragment currentFragment = getCurrentFragment();
if (currentFragment != null)
getSupportFragmentManager().beginTransaction().remove(currentFragment).commit();
getSupportFragmentManager().beginTransaction().add(R.id.container_main, fragment, tag).commit();
}
public Fragment getCurrentFragment()
{
FragmentManager manager = getSupportFragmentManager();
return manager.findFragmentById(R.id.container_main);
}
private void popBackStack()
{
FragmentManager fragmentManager = getSupportFragmentManager();
int total = fragmentManager.getBackStackEntryCount();
for (int i = 0; i < total; i++)
{
fragmentManager.popBackStack();
}
}
You can use findFragmentByTag(String tag) method provided by FragmentManager to check if the fragment already exists or not.
Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG);
For this to work, you need to commit your fragment with that TAG using -
fragmentTransaction.replace(R.id.outbound_dashboard_hourly_queued, fragment, TAG);
please follow the count checking before replace if the count == 0 add else replace your code must be like
public void loadFragment(Fragment fragment){
FragmentManager fragmentManager = Objects.requireNonNull(getActivity()).getSupportFragmentManager();
// Begin Fragment transaction.
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();// Replace the layout holder with the required Fragment object.
if(fragmentManager.getFragments().size() == 0){
fragmentTransaction.add(R.id.outbound_dashboard_hourly_queued, fragment).commit();
}else {
fragmentTransaction.replace(R.id.outbound_dashboard_hourly_queued, fragment).commit();
}
// Commit the Fragment replace action.
}
please try with this and let me know.

Go back to the default fragment

I have a Android app with one activity and two fragments. First fragment (MainFragment) show a list of "items" and second (DetailsFragment) display a item's details (very basic).
On the normal flow, the activity start and show first fragment and the second is shown when a item is clicked.
But the second fragment can be shown directly throught click on a notification (by putting extra arguments to the activity).
String id = getIntent().getStringExtra("id");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (id != null) {
fragment = new DetailsFragment();
Bundle args = new Bundle();
args.putString("id", id);
fragment.setArguments(args);
} else {
fragment = new MainFragment();
}
ft.replace(R.id.main, fragment);
ft.commit();
In the second case, the problem is : How to open MainFragment when clicking back from DetailsFragment ? Actually the app finish because only the second fragment has been created.
First way: Its very simple. You just need to use addToBackStack(null). It will save your desired fragment and when you use backpressed it will open that one.
Do something like this:
if (id != null) {
fragment = new DetailsFragment();
Bundle args = new Bundle();
args.putString("id", id);
fragment.setArguments(args);
ft.replace(R.id.main, fragment);
ft.commit();
} else {
fragment = new MainFragment();
ft.replace(R.id.main, fragment).addToBackStack(null);
ft.commit();
}
Second way: in your DetailsFragment's onResume() method write this code.
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
fragment = new MainFragment();
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main, fragment);
fragmentTransaction.commit();
return true;
}
return false;
}
});
}
Add the main fragment in the onCreate() of the activity and override the onBackPressed() in the main activity
FragmentTransaction mFragmentTransaction = fragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container_recharege, fragment);
mFragmentTransaction.commit();
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 1) {
fragmentManager.popBackStack();
} else {
super.onBackPressed();
}
}
This is very common situation in Android, and simply saying you can just add it to backstack. So when user presses back button he will see the previous fragment(MainFragment).
getFragmentManager()
.beginTransaction()
.addToBackStack(yourFragment.getClass().getSimpleName())
.replace(R.example.container, yourFragment)
.commit();
Have a read official Android documentation about the back stack
UPDATE:
If you open DetailsFragment directly(without opening MainFragment) then you should check the back stack, if it is empty then open MainFragment manually. Here is the full code:
if (getSupportFragmentManager().getBackStackEntryCount() == 0) // empty back stack{
getFragmentManager()
.beginTransaction()
.replace(R.example.container, MainFragment)
.commit();
}
You can use something like this on your back press or back button clicked
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
fragment = new MainFragment();
ft.replace(R.id.fragment_container, frag);
ft.commit();
add fragment like this
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(containerId, fragment);
ft.addToBackStack(backStateName);
ft.commit();
and in your activity backpress put this
getSupportFragmentManager().popBackStack();

How to check if the fragment exists

I am trying to talk to the fragments from activity.
Here in my MainActivity I am adding multiple fragments ok so for fine.
My main requirement is I don't want to add if fragment is already added.
So how can we check this condition?
Please help me some one.
code:-
private void intializingFragments(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private View.OnClickListener intialization() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
int getId = v.getId();
if (getId == R.id.first) {
intializingFragments(new Fragment1());
} else if (getId == R.id.second) {
intializingFragments(new Fragment2());
} else if (getId == R.id.third) {
intializingFragments(new Fragment3());
}
}
};
}
You can use findFragmentByTag() or findFragmentById() functions to get a fragment. If mentioned methods are returning null then that fragment does not exist.
Fragment fragmentA = fragmentManager.findFragmentByTag("frag1");
if (fragmentA == null) {
// not exist
} else {
// fragment exist
}
for example:- http://wiki.workassis.com/android-load-two-fragments-in-one-framelayout/
You may find fragment in fragmentmanager:
List<Fragment> frags = getSupportFragmentManager().getFragments();
for (Fragment f : frags) {
<find what you want>...
}
Or you may add fragment with tag:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frame, new MyFragment(), "frag1")
.commit();
And find by tag
getSupportFragmentManager().findFragmentByTag("frag1");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment topFragment = fragmentManager.findFragmentById(R.id.container);
FragmentA fragmentA = new FragmentA();
if(topFragment!= null)
{
transaction.remove(topFragment);
transaction.add(R.id.container, fragmentA, "FA");
transaction.commit();
}
else
{
transaction.add(R.id.container, fragmentA, "FA");
transaction.commit();
}
try this
private void intializingFragments(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment topFragment = fragmentManager.findFragmentById(R.id.container);
if(topFragment!= null)
{
fragmentTransaction.remove(topFragment);
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else
{
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
How to check whether a fragment exists, without knowing its resource ID or tag:
// MyActivity.kt
val exists: Boolean = supportFragmentManager
.fragments
.filterIsInstance<MyFragment>()
.isNotEmpty()
There are many ways by which you can track the last added fragment. The simplest one is by finding the tag within fragment manager. Here is the sample code of it:
public boolean isFragmentPresent(String tag) {
Fragment frag = getSupportFragmentManager().findFragmentByTag(tag);
if (frag instanceof HomeFragment) {
return true;
} else
return false;
}
Alternatively, you can use your own variable to check whether the last added fragment is the same as the current fragment. Here is the sample code for it:
public boolean isCurrentFragment(Fragment fragment) {
if (fragment instanceof HomeFragment && getLastAddedFragment() instanceof HomeFragment) { // getLastAddedFragment() is a method which return the last added fragment instance
return true;
} else
return false;
}
And you can use it like:
if (isCurrentFragment(new HomeFragment())) {
// Last added Fragment is the HomeFragment
}
You can go for popBackStack Pop the last fragment transition from the manager's fragment back stack. If there is nothing to pop, false is returned. enter link description here
You can get the list of previously added fragments from the fragment manager. Then just check whether the list contains your fragment object or not.
getSupportFragmentManager().getFragments().contains(yourFragment);
This one doesn't work
!getSupportFragmentManager().getFragments().contains(fragment)
This works for me
getSupportFragmentManager().findFragmentByTag(fragment::class.java.getSimpleName()) == null

initialize fragment in android

I only know how to add fragment and remove.
also show and hide.
I just want to initialize fragment.
onCreate {
getFragmentManager().beginTransaction().add(R.id.top_container, new AuthProgressDialog(), AuthProgressDialog.class.getSimpleName()).commit();
getFragmentManager().beginTransaction().hide( getFragmentManager().findFragmentByTag(AuthProgressDialog.class.getSimpleName()) ).commit();
}
This is bad code, isn't it?
If you have any idea, please let me know.
Thanks.
This is sample method which you can define inside your FragmentActivity and call from any of the fragment. in which if you want to allowing adding to backstack than just remove comment line from transaction.addToBackStack("back"); and check popup backstack as per your requirement inside FragmentActivity.
public void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FormFragment();
break;
case 1:
fragment = new HomeFragment();
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager
.beginTransaction();
if (position != 0)
// transaction.addToBackStack("back");
transaction.replace(R.id.main_ll_container, fragment).commit();
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
Use this code :
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fraggy = new DummyFragment();
fragmentTransaction.add(R.id.fragment_container, fraggy);
fragmentTransaction.commit();

Fragment dismiss after tap on Back button

I have two Fragments - FragmentA and FragmentB.
I try to show FragmentB from FragmentA.
FragmentB fragmentB = new FragmentB();
MainActivity activity = (MainActivity) getActivity();
int fragmentContainer = activity.getFragmentContainer();
FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(fragmentContainer, fragmentB);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
fragmentA = new FragmentA(getSupportFragmentManager());
//...
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(FRAGMENT_CONTAINER,fragmentA);
fragmentTransaction.commit();
}
FragmentB is showed, but when i click on back button i have a next situation - FragmentB was dismissed, but FragmentA not showed.
Why this happens and what i need to edit to get a correct result?
getActivity().getChildFragmentManager().beginTransaction();
use this it may be works inside fragmentB
Thanks to New Developer for provided link.
All that we need it's just add a
#Override
public void onBackPressed(){
if (getSupportFragmentManager().getBackStackEntryCount() == 1){
finish();
}
else {
super.onBackPressed();
}
}
and
private void replaceFragment (Fragment fragment){
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null){ //fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content_frame, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
}
}
and manage fragments in activity.
So if we need a swap fragments just call :
replaceFragment(new MySwappingFragment());

Categories

Resources