Android Start Fragment from Activity's back press - android

Hello I want to start a Fragment on back-press of Simple Activity
I have done like this
public boolean onKeyDown(int keyCode, KeyEvent event) {
Fragment fragment = null;
fragment = new MainActivity();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();
return true;
}
return super.onKeyDown(keyCode, event);
}
But not working..

Try this:
#Override
public void onBackPressed() {
android.support.v4.app.FragmentManager mFragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragmentView, new Fragment()).commit();
}

Try to use below code.
#Override
public void onBackPressed() {
Fragment fragment = null;
fragment = new MainActivity();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();
}
Hope it will work.

Related

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 get back to previous fragment in Android

I want to move back to my previous fragment when I click on the back button. What I am doing is not working.
The code for fragment replacement:
Fragment fragment=new MyFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in,R.anim.slide_out);
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
The code for catch hit of Back button:
#Override
public void onResume() {
super.onResume();
getActivity().invalidateOptionsMenu();
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) {
getActivity().finish();
getActivity().overridePendingTransition(R.anim.slide_enter, R.anim.slide_exit);
return true;
}
return false;
}
});
I have also tried
getActivity().getSupportFragmentManager().popBackStack();
Change like this this mat help
Fragment fragment=new MyFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in,R.anim.slide_out);
fragmentTransaction.replace(R.id.container_body, fragment).addToBackStack(null);
fragmentTransaction.commit();
Let me know if any error
you can do like below.
DetailsFragment detailsFragment = new DetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("ID", Id);
detailsFragment.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.detail_container, detailsFragment);
transaction.addToBackStack(this.getClass().getSimpleName());
transaction.hide(DetailsFragment.this);
transaction.commit();

How to call fragment from a java class in android?

I am calling a one fragment from a java class, on click of one textview I am calling one fragment this is my code of onclick.
returnTheProduct.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = context.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProductReturnFragment productReturnFragment = new ProductReturnFragment();
fragmentTransaction.replace(R.id.layout_marketplace_forms, new MarketPlaceFormsActivity());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
Add like :
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (isBackPressed)
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.framelayout,attachedfragmentHere);
fragmentTransaction.setCustomAnimations(R.anim.fade_in,R.anim.fade_out);
fragmentTransaction.commit();
Just import the following two statements:
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
And,
private FragmentTransaction mFragmentTransaction;
private FragmentManager mFragmentManager;
.....
Then on your click listener you can write below code :
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.layout_marketplace_forms, new ProductReturnFragment());
mFragmentTransaction.commit();
Hope you get your answer. :D
From class call Activity on which you are calling fragments like below code.
Intent intent = new Intent(context, CallingActivity.class);
intent.putExtra("key", "value");
context.startActivity(returnFormIntent);
In your CallingActivity define below code.
private FragmentManager fragmentManager = getSupportFragmentManager();
private YourFragment yourFragment;
if (getIntent().hasExtra("key")) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
yourFragment = new YourFragment();
fragmentTransaction.add(R.id.layout_your_fragment, yourFragment);
fragmentTransaction.commit();
}
like above we can call fragments from other nonActivity classes.

Accessing fragment method through activity

I'm developing a kiosk app where people can walk to and order something.
I have a single activity with bunch of different fragments (order, review, pay, etc). Some replace each other, and some get added. The activity has a single fragment hardcoded R.id.fragmentContainer and the rest are programmatically added and tagged.
Now what I want is to have a function in my activity that calls one of the elements of the fragments (look at updateReceivedData()) but for some reason I'm not able to do so and I get cannot resolve method adjustPriceFunc.
I'm adding the code so someone could tell me what I'm doing wrong. The app would normally talk to some hardware so I took out a bunch of those details from the code to make it easier to read.
public class MainActivity extends FragmentActivity {
private final String TAG = MainActivity.class.getSimpleName();
List<WeakReference<Fragment>> fragList = new ArrayList<WeakReference<Fragment>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.backbone);
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new Fragment();
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment, "SystemDownFragment")
.addToBackStack(null)
.commit();
}
}
public void orderFunc() {
Log.d(TAG, "orderFunc()");
if(sendingLogFlag) attemptSend(TAG + ":orderFunc()");
for(int i = 0; i < getActiveFragments().size(); i++) {
getSupportFragmentManager().beginTransaction().remove(getActiveFragments().get(i)).commit();
}
Fragment newFragment = new Fragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragmentContainer, newFragment, "OrderFragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
public void checkoutFunc() {
Log.d(TAG, "checkoutFunc()");
if(sendingLogFlag) attemptSend(TAG + ":checkoutFunc()");
for(int i = 0; i < getActiveFragments().size(); i++) {
getSupportFragmentManager().beginTransaction().remove(getActiveFragments().get(i)).commit();
}
Fragment newFragment = new Fragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragmentContainer, newFragment, "CheckOutFragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
public void reviewFunc(){
Log.d(TAG, "reviewFunc()");
if(sendingLogFlag) attemptSend(TAG + ":reviewFunc()");
if(getActiveFragments().size() > 1){
Fragment frag = getSupportFragmentManager().findFragmentByTag("ReviewFragment");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
ft.remove(frag);
ft.commit();
}
else {
Fragment newFragment = new Fragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.add(R.id.fragmentContainer, newFragment, "ReviewFragment");
ft.commit();
}
getSupportFragmentManager().executePendingTransactions();
}
public void payFunc(boolean enabled){
Log.d(TAG, "payFunc()");
if(sendingLogFlag) attemptSend(TAG + ":payFunc()");
if(!enabled){
Fragment frag = getSupportFragmentManager().findFragmentByTag("PayFragment");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
ft.remove(frag);
ft.commit();
}
else {
Fragment newFragment = new Fragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.add(R.id.fragmentContainer, newFragment, "PayFragment");
ft.commit();
}
getSupportFragmentManager().executePendingTransactions();
}
public void doneFunc() {
Log.d(TAG, "doneFunc()");
for(int i = 0; i < getActiveFragments().size(); i++) {
getSupportFragmentManager().beginTransaction().remove(getActiveFragments().get(i)).commit();
}
Fragment newFragment = new Fragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.add(R.id.fragmentContainer, newFragment, "StartupFragment");
ft.commit();
}
#Override
public void onAttachFragment (Fragment fragment) {
fragList.add(new WeakReference(fragment));
}
public List<Fragment> getActiveFragments() {
ArrayList<Fragment> ret = new ArrayList<Fragment>();
for(WeakReference<Fragment> ref : fragList) {
Fragment f = ref.get();
if(f != null) {
if(f.isVisible()) {
ret.add(f);
}
}
}
return ret;
}
private void updateReceivedData() {
Fragment frag = getSupportFragmentManager().findFragmentByTag("PayFragment");
frag.adjustPriceFunc();
}
You are trying to use method adjustPriceFunc() from class Fragment, which is not part of it.
Use this code, where MyFragment is your proper fragment (I assume it should be PayFragment).
private void updateReceivedData() {
Fragment frag = getSupportFragmentManager().findFragmentByTag("PayFragment");
if (frag instanceof MyFragment) {
frag.adjustPriceFunc();
}
}
There is few mistakes here in the code
In orderFunc, checkoutFunc etc. add remove to the transaction and call commit once after the loop, like
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
for(int i = 0; i < getActiveFragments().size(); i++) {
transaction.remove(getActiveFragments().get(i));
}
transaction.commit();
You get compilation error in updateReceivedData because Fragmentdoes not have adjustPriceFunc() method. You need either (cleaner approach) create interface with adjustPriceFunc() method, let your fragment implement it and then your updateReceivedData will look like follows:
private void updateReceivedData() {
InterfaceWithAdjustPriceMethod frag = (InterfaceWithAdjustPriceMethod) getSupportFragmentManager().findFragmentByTag("PayFragment");
frag.adjustPriceFunc();
}
Storing reference to fragment is a bad practice, even if it is WeakReference.
Better use this way:
Fragment fragment = getSupportFragmentManager().findFragmentByTag("tag");

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