i want to know, how to call a fragment from dialog box click action in android. The dialog box is in another activity.
below is the dialog box section code
public static void Bookingconfirm(final Context _context, String title,String strMessage)
{
final Dialog dialog1 = new Dialog(_context);
Log.e("Point","1");
dialog1.setContentView(R.layout.booking_success);
dialog1.setCanceledOnTouchOutside(true);
dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog1.findViewById(R.id.d_location);
LinearLayout btnok = (LinearLayout) dialog1.findViewById(R.id.booking_ok);
btnok.setOnClickListener(new OnClickListener()
{
#SuppressLint("NewApi") #Override
public void onClick(View arg0)
{
Log.e("Point","2");
//i wanted the click to fragment here
// parent class of fragment Home.java and fragment is booking.java
}
});
dialog1.show();
}
Fragment fragment= booking.newInstance();
Home mainActivity = (Home) context;
FragmentManager manager = mainActivity.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, fragment, "Frag");
transaction.commit();
Try the above code from your dialog click Listener ...Hope this helps
try the below code:
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new booking());
fragmentTransaction.commit();
Haroon and pradeep answer wont work.
you can pass FragmentManager to your dialog class like this:
import android.support.v4.app.FragmentManager
class TestDialog(val fragmentManager:FragmentManager) {
fun show()
{
showFragmentButton.setOnClickListener{
val fragmentTransaction = fragmentManager.beginTransaction()
val fragment = PurchaseDetail()
fragmentTransaction.replace(R.id.container, fragment, "cashier_fragment")
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
}
}
}
and in your fragment:
TestDialog(getFragmentManager()).show()
Related
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();
}
I am making a simple demo project using Fragments, in which i am calling SecondFragment from FirstFragment on button click.
And i called SecondFragment without any issue, but i getting view of both the Fragments SecondFragment and FirstFragment
So where i am doing mistake ?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new FirstFragment()).commit();
}
}
public static class FirstFragment extends Fragment {
Button buttonCallSecondFragment;
public FirstFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container,
false);
buttonCallSecondFragment = (Button) rootView.findViewById(R.id.button1);
buttonCallSecondFragment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentManager fm = getFragmentManager();
SecondFragment fragment = new SecondFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container, fragment);
ft.commit();
}
});
return rootView;
}
}
public static class SecondFragment extends Fragment {
public SecondFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second, container,
false);
return rootView;
}
}
}
You need to remove the first fragment, you can do that either by usingreplace or first calling remove then add
To be able to press the back button add the transaction to the back stack,you do that by calling addToBackStack(tag) on your fragment manager. Tag may be null.
You are adding fragment on already displaying fragment in your android app.
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container, fragment);
ft.commit();
Do not add fragment but replace fragment when already one fragment is loaded on activity.
So for implementing that :
Please add your code in OnCreate() and add below code to your click listener :
FragmentManager fm = getFragmentManager();
SecondFragment fragment = new SecondFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container, fragment);
ft.addToBackStack(null);
ft.commit();
Thank you.!!
if you want to replace fragment you should call replace in place of add :
buttonCallSecondFragment = (Button) rootView.findViewById(R.id.button1);
buttonCallSecondFragment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentManager fm = getFragmentManager();
SecondFragment fragment = new SecondFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
You are adding the fragment so it will come on top of another fragment give background color to rootview of scecond fragment
you can also load that as Nested fragment
public void addFragB() {
FragmentManager childFragMan = getChildFragmentManager();
FragmentTransaction childFragTrans = childFragMan.beginTransaction();
SecondFragment 2ndfrag = new SecondFragment();
childFragTrans.add(R.id.fragA_LinearLayout, 2ndfrag);
//childFragTrans.addToBackStack("");
childFragTrans.commit();
}
No, you cannot communicate between fragments like this. You need to communicate between fragments via the container activity.
I suggest, you make a navigation method in your activity and switch/call between fragments from there.
Below is a small snippet:
In your container activity:
Fragment fragment;
public void navigateTo(Fragment newFragment,boolean addToBackStack) {
this.fragment = newFragment;
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.fragment_container, newFragment);
if(addToBackStack)
ft.addToBackStack(fragment.getClass().getSimpleName());
ft.commit();
}
If you are going from Fragment1 to Fragment2 then in your Fragment1 do the following:
((YourContainerActivity) getActivity()).navigateTo(new Fragment2(),false); //if you want to add to back stack make 2nd argument true.
private void selectItem(int position) {
selectedPosition = position;
// update the main content by replacing fragments
fragment = null;
fragmentStack = new Stack<Fragment>();
switch (position) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
}
//redirect the screen
if (fragment != null) {
fragmentManager = getSupportFragmentManager();
redirectScreen(fragment);
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(title[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
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();
}
}
I have to call a fragment class from baseAdapter class. I have created a method in main fragment class like this
public void switchContent(Fragment fragment) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new Reply_ozoneFragment()).commit();
}
and calling this method in adapter class like this.
holder.bt_reply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
fragment.switchContent();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new Reply_ozoneFragment());
fragmentTransaction.commit();
/*Intent reintent = new Intent(context,Reply_ozoneFragment.class);
//reintent.putExtra("userid", S);
context.startActivity(reintent);
*/
}
});
but this is not working properly and my app crashes every time. Please tell me what mistake I am doing here.
remove fragment.switchContent(); from your adapter button onclick() method and change
FragmentManager fm = getFragmentManager();
to
FragmentManager fm = getActivity().getSupportFragmentManager()
I have a Fragment, and from that Fragment I show up a DialogFragment, I want the DialogFragment to send message to the Fragment, or rech the Fragment's variables. How can I do tis?
You probably want to utilize a Listener pattern for this. Here's a quick example to get you started:
public class MyDialogFragment extends DialogFragment {
public interface MyDialogFragmentListener {
public void abstract onDialogMessage(int someValueIWantToSendToFragment);
}
private MyDialogFragmentListener mListener;
....
public void setListener(MyDialogFragmentListener listener) {
mListener = listener;
}
}
and then whenever you need to send some bit of data to your fragment from the dialog, call mListener.onDialogMessage(someValue);
Make sure that when you create your dialogfragment, you call setListener on it with an instance of MyDialogFragmentListener.
you can put this code where you want in the dialogFragment:
Bundle args = new Bundle();
args.putString("message",myMessage);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment = Fragment.instantiate(getActivity(), MyFragment.class.getName(), args);
ft.replace(R.id.details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
for example in the onCreate of dialog fragment we send a message, using bundle:
public static class MyDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String myMessage="Hello Fragment";
Bundle args = new Bundle();
args.putString("message",myMessage);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment = Fragment.instantiate(getActivity(), MyFragment.class.getName(), args);
ft.replace(R.id.details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_dialog_about)
.setTitle(R.string.about)
.setMessage(R.string.about_message)
// ...
.create();
}
}
in MyFragment I can get my message, using only this line:
getArguments().getString("message");