Currently, my main activity has a description field which opens a fragment when the user clicks on the description. On the fragment there is a text field and a button, when I click the button, I want to close the fragment and go back to my activity.
How can I achieve this?
I have added an onClickListener to my fragment to capture the click on the button. The toast message gets printed, but the fragment is not removed/closed.
descDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Dismissed", Toast.LENGTH_LONG).show();
getActivity().getFragmentManager().popBackStackImmediate();
}
});
I have the onClickListener in the onCreateView of the fragment. Is this correct?
Thanks in advance!
EDIT:
I am adding my fragment like this:
((MainActivity)context).getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, frag).commit();
try this first add the fragment to backstack like this
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(..............);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Then remove the fragment like this:-
FragmentManager fm = getActivity().getSupportFragmentManager();
if(fm.getBackStackEntryCount()>0) {
fm.popBackStack();
}
to remove all fragments
FragmentManager fm = getActivity().getSupportFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
try this
getActivity().getSupportFragmentManager().popBackStack();
Use getFragmentManager().popBackStack();
try to using following code:
public void fragmentReplace() {
if (getSupportFragmentManager().findFragmentByTag(new TermsAndConditionFragment().getClass().getName()) != null) {
getSupportFragmentManager().popBackStack(new TermsAndConditionFragment().getClass().getName(),
FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
super.onBackPressed();
}
in main Activity in descDismiss button clickListener insert below code:
descDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Dismissed", Toast.LENGTH_LONG).show();
fragmentReplace();
}
});
My way to add fragments:
fragmentTransaction = fragmentManager.beginTransaction();
frmInicio fragment = new frmInicio();
fragmentTransaction.add(R.id.content_menu_layout, fragment,"frm_inicio");
fragmentTransaction.commit();
My way to remove
//frm_inicio
Fragment frm = fragmentManager.findFragmentByTag("frm_inicio");
if(frm!=null){
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(frm);
fragmentTransaction.commit();
}
Related
ImageButton imageButton3 =(ImageButton)view.findViewById(R.id.item_two_timer_id);
imageButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.replace(R.id.container2_main , new TimerFragment2())
.addToBackStack(null)
.commit();
While adding fragment add a tag to identify it.get the fragment by tag and see if the fragment is present.If it is not present create a new Instance and add it.
ImageButton imageButton3 = (ImageButton) view.findViewById(R.id.item_two_timer_id);
imageButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimerFragment2 timerFragment2;
timerFragment2 = (TimerFragment2) getFragmentManager().findFragmentByTag(TimerFragment2.class.getSimpleName());
if(timerFragment2==null){
timerFragment2=new TimerFragment2();
getFragmentManager().beginTransaction()
.replace(R.id.container2_main, timerFragment2,TimerFragment2.class.getSimpleName())
.addToBackStack(TimerFragment2.class.getSimpleName())
.commit();
}else {
//Dont create fragment again
}
}
});
please try this code if you are setting one fragment
private void initFragment() {
SelectTypeFragment fragment = new SelectTypeFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right); //if you want to set animation
fragmentTransaction.replace(R.id.fl_addvehicle, fragment);
fragmentTransaction.commit();
}
if you are replacing one fragment to with another.
void goToNextFragment() {
((CreateOfferActivity) this.getActivity()).setCreateOfferModel(createOfferModel);
SelectVehicleFragment fragment = new SelectVehicleFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
fragmentTransaction.replace(R.id.fl_create_offer, fragment).
addToBackStack("select_vehicle");
fragmentTransaction.commit();
}
You can check it in Fragment but first,
You need to create an object of Fragment TimerFragment2 and check if it's visible or not in timerFragment.isVisible()
ImageButton imageButton3 =(ImageButton)view.findViewById(R.id.item_two_timer_id);
TimerFragment2 timerFragment = new TimerFragment2();
imageButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!timerFragment.isVisible())
getFragmentManager().beginTransaction()
.replace(R.id.container2_main , timerFragment)
.addToBackStack(null)
.commit();
I have a Navigation drawer activity and it contains couple of Fragments. My problem is I want to call the Navigation drawer activity class in button click which should have fragment B, by default navigation drawer has fragment A.
I am posting my code here:
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),Navigation.class));
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.content_frame, new FragmentB());
tx.commit();
finish();
}
});
Where content_frame is the area were I want to replace fragment B view..
try this approach
in your button click send extra data to check what fragment you need
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Navigation.class);
intent.putExtra("SELECTEDVALUE", 2);//1 for fragament A use 2 for fragment B
startActivity(intent);
}
});
Now, in your oncreate() method of Navigation Activity
Bundle extras = savedInstanceState != null ? savedInstanceState : getIntent().getExtras();
int selectedValue = extras.getInt("SELECTEDVALUE");
switch (selectedValue) {
case 1:
goToFragment(new A(), false);
break;
case 2:
goToFragment(new B(), false);
break;
finally gotoFragment is...
private void goToFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container, fragment).commit();
}
Try below code;
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = new FragmentB();
FragmentManager fm =getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
});
Just make an instance of FragmentB like this
FragmentB fragment - new FragmentB();
and then pass it like this .
tx.replace(R.id.content_frame, fragment);
tx.commit();
now you can access all the variables and methods of fragment from your activity using instance fragment. like this fragment.methodName();
Try this code:
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame, new FragmentB(), "fragmentB").addToBackStack(null).commit();
}
});
hope it'll solve your problem.
I'm a newbie in android and using android studio 2.2
In my app I've used different fragments and they appear when user click on an ImageView and I've used addToBackStack function for the device back button. It takes me to the exactly previous fragment but it does not highlight the previous Imageview according to the statements when clicked on back button.
Here is the code for fragments
public void dates(View view)
{
if(frag != null)
{
home1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon));
subs1.setBackgroundDrawable(getResources().getDrawable(R.drawable.subscription_icon));
noti1.setBackgroundDrawable(getResources().getDrawable(R.drawable.noti_icon));
settings1.setBackgroundDrawable(getResources().getDrawable(R.drawable.setting_icon));
date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.date_icon_black));
date.setTextColor(0xFF000000);
getSupportActionBar().setTitle("Available Dates");
frag = new AvailableDates();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container1,frag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
public void subscription(View view)
{
if (frag != null)
{
home1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon));
subs1.setBackgroundDrawable(getResources().getDrawable(R.drawable.subscription_icon_black));
noti1.setBackgroundDrawable(getResources().getDrawable(R.drawable.noti_icon));
settings1.setBackgroundDrawable(getResources().getDrawable(R.drawable.setting_icon));
date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.date_icon));
subs.setTextColor(0xFF000000);
getSupportActionBar().setTitle("Subscriptions");
frag = new Subscription();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container1,frag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
If you want to hightlight/changes when press back, you need to control manually back press like this in your activity:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
// Now, your AvailableDates fragment resumes, you can hightlight your views again
} else {
super.onBackPressed();
}
}
all!
I have 2 fragments. First one appears at start, second one adds with button "Add", using the same container.I am trying to add fragment to the back stack with method addToBackStack, but when I click "back-button" my app hides instead of showing me the first fragment. What is wrong?
public class MainActivity extends AppCompatActivity {
FirstFragment fragment1;
SecondFragment fragment2;
FragmentTransaction fragmentTransaction;
FragmentManager fm;
Button add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fragment1 = new FirstFragment();
fragment2 = new SecondFragment();
add = (Button) findViewById(R.id.add);
fm = getFragmentManager();
fragmentTransaction = fm.beginTransaction();
fragmentTransaction.add(R.id.container, new FirstFragment());
fragmentTransaction.commit();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, new SecondFragment());
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
}
addToBackStack() on fragment transaction is not enough, we have to handle the popping up of the back stack upon Back button pressed by ourselves.
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
I have a fragment activity from where i can start my fragments which contain a viewpager. In my fragment activity I have added this piece of code.
fragment = new ItemPagerFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
Now when I press back button only blank screen appears and it does not lead me to my fragment activity.
What wrong i might be doing?
Use this in activity that holds fragment.
#Override
public void onBackPressed() {
if (fragmentManager.getBackStackEntryCount() > 1) {
fragmentManager.popBackStack();
} else
finish();
}
Try this way,
// Create new fragment and transaction
Fragment newFragment = new ItemPagerFragment();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Modify your code
#Override
public void onBackPressed() {
if(some condition) {
// do something
} else {
super.onBackPressed();
}
}
Please follow this link
Handling back button press Inside Fragments
You have to tell to the fragment manager that the back button was pressed. Override onBackPressed on your Activity
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
}
private void changeFragment (Fragment fragment){
String backStackName = fragment.getClass().getName();
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate (backStackName, 0);
if (!fragmentPopped){ //fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(backStackName );
ft.commit();
}
}
While launching fragment assign a TAG to each fragment.When you want to back press check the existence of an fragment using assigned TAG name and then do corresponding action.for example:
private final static String TAG_FRAGMENT = "TAG_FRAGMENT";
//when want to add fragment to view
private void showFragment() {
final Myfragment fragment = new MyFragment();
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, fragment, TAG_FRAGMENT);
transaction.addToBackStack(null);
transaction.commit();
}
//in activity back pressed check the existence of fragment by TAG
#Override
public void onBackPressed() {
final Myfragment fragment = (Myfragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if (fragment.allowBackPressed()) { // and then you define a method allowBackPressed with the logic to allow back pressed or not
super.onBackPressed();
}
}