Set item on navigation view as selected from fragment - android

When moving to a different fragment I want the corresponding item in the navigation menu to be highlighted. This should be done from the fragment itself.
Below is the code present in the fragment:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispName = dispNameET.getText().toString();
myRef.setText(dispName);
//going to another fragment
Fragment fragment = new ListFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, fragment);
fragmentTransaction.commit();
}
});
After this the navigation view shows wrong item as highlighted.
Please help

Your code should look like this
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispName = dispNameET.getText().toString();
myRef.setText(dispName);
//going to another fragment
Fragment fragment = new ListFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, fragment);
fragmentTransaction.commit();
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id./*id of nav bar*/);
navigationView.setCheckedItem(R.id./*id of menu item to be highlighted*/);
}
});

NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id./*id of nav bar*/);
navigationView.setCheckedItem(R.id./*id of menu item to be highlighted*/);
Put this code in the onClick method or in the beginning of required fragment

Related

Android Studio Navigation Drawer fragments overlapping

I've added a Navigation drawer activity to my project and I'm trying to add items as fragments. This is what I have done in the main activity.
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.nav_host_fragment, new HomeFragment());
fragmentTransaction.commit();
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item)
{
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
int id = item.getItemId();
if (id == R.id.nav_home)
{
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, new HomeFragment());
fragmentTransaction.commit();
}
else if(id == R.id.Shopping_list)
{
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, new ShoppingListFragment());
fragmentTransaction.commit();
}
else if(id == R.id.nav_Language)
{
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, new FragmentLang());
fragmentTransaction.commit();
}
The default fragment is Home which is working fine and as expected BUT the other fragments are overlapping with the Home Fragment. (The HomeFragment is the only one that's working fine).
I've done something like this inside every Fragment class:
public class ShoppingListFragment extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_shopping_list, container,false);
return view;
}
}
I can't see where the mistake is. everything looks good but all other fragments are showing over the HomeFragment.
fragment manager maintains the stack of all the previous fragments that are replaced sometimes the back stack fragments overlap with the fragment we replaced, add this line
fragmentManager.popBackStack();
like this,
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, new HomeFragment());
fragmentManager.popBackStack();
fragmentTransaction.commit();
Hope will help. Happy coding :)

How to communicate between FragmentActivity and Fragment?

This use Navigation Drawer, and use Tab, and use Fragment.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DrawerLayout myDrawerLayout;
NavigationView myNavigationView;
FragmentManager myFragmentManager;
FragmentTransaction myFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
myNavigationView = (NavigationView) findViewById(R.id.nav_drawer) ;
myFragmentManager = getSupportFragmentManager();
myFragmentTransaction = myFragmentManager.beginTransaction();
myFragmentTransaction.replace(R.id.containerView, new HomeFragment()).commit();
myNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem selectedMenuItem) {
myDrawerLayout.closeDrawers();
if (selectedMenuItem.getItemId() == R.id.nav_item_select1) {
FragmentTransaction fragmentTransaction = myFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new Select1()).commit();
}
return false;
}
}
}
}
Pyeondo.java
You have to use same fragment in which you are setting bundle.
Replace new select1() with fragment
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
bundle.putString("Slocale1",SbtnsLocale.getText().toString());
bundle.putString("Slocale2",SbtneLocale.getText().toString());
bundle.putString("Sdate1",StxtsDate.getText().toString());
bundle.putString("Sdate2",SStxtsDate.getText().toString());
bundle.putString("Sseat",StxtSeat.getText().toString()); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.containerView, fragment).commit();
You already has fragment instance
fragment.setArguments(bundle);
and you are setting argument in that instance so don't create new one, use it
fragmentTransaction.replace(R.id.containerView, fragment).commit();

Fragment keeps on adding when the button is clicked

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();

Remove fragment from activity when clicking button?

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();
}

View Issue Calling SecondFragment from FirstFragment

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);
}
}

Categories

Resources