I have ,
Two fragments (Fragment1,Fragment2).
Two buttons (Btn1 in frag1 , Btn2 in frag2).
A bottom navigation view.
On clicking the Btn in frag1 , we will be directed to frag2.
On clicking the Btn in frag2 , we will be directed to frag1.
while directing from frag(1->2 or 2->1), the icon on the bottom navigation view stays the same
Is there a way to highlight that icon with respect to the loaded fragment?
On Click Listener for btn in frag1
this.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.body_container, new Fragment2()).commit();
On Click Listener for btn in frag2
this.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.body_container, new Fragment1()).commit();
OnItemSelectedListener for bottom nav in MainActivity Code
((BottomNavigationView)findViewById(R.id.bottom_nav)).setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener(){
Fragment clickedFragment = null;
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.one: clickedFragment = new Fragment1(); break;
case R.id.two: clickedFragment = new Fragment2(); break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.body_container, clickedFragment).commit();
return true;
}
});
The setOnItemSelectedListener is only triggered whenever the selected item of the BottomNavigationView changes. What you are currently doing is changing the current displayed fragment. Instead of changing the fragment, you should set the selected item of the BottomNavigationView instead. Something like this should work
((BottomNavigationView) findViewById(R.id.bottom_nav)).setSelectedItemId(R.id.your_menu_item_id);
Create a class temp in the same package as the main activity is in and add the below field to it.
public static BottomNavigationView bottomNavigationView;
Just go through the code, I explained in comments.
Main Activity Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavView = temp.bottomNavigationView = findViewById(R.id.bottom_nav);
//This line, initially when the app is opened, displays the fragment1 by default
getSupportFragmentManager().beginTransaction().replace(R.id.body_container, new Fragment1()).commit();
bottomNavView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment clickedFragment = null;
switch (item.getItemId()) {
case R.id.one: clickedFragment = new Fragment1(); break;
case R.id.two: clickedFragment = new Fragment2(); break;
}
//This line replaces the fragment when user clicks on icon of bottom navigation view
getSupportFragmentManager().beginTransaction().replace(R.id.body_container, clickedFragment).commit();
return true;
}
});
}
3.OnViewCreated in Fragment1
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.btn_to_frag2).setOnClickListener(l->{
temp.bottomNavigationView.setSelectedItemId(R.id.two);
});
}
4.OnViewCreated in Fragment2
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.btn_to_frag1).setOnClickListener(l->{
temp.bottomNavigationView.setSelectedItemId(R.id.one);
});
}
Just make sure that the setOnItemSelectedListener has a return value of true
It works fine without setting the setSelectedItemId
Related
I have already add an bottom navigation bar into my project with 3 fragments (Home_fragment, Wallet_fragment,Account_fragment). I have added login button in Account_fragment. Now i want that When ever i click on login button login_fragment(afterlogin_fragment) open with bottom navigation bar.
I have attaching a link to video showing my problem. link -- https://cloud.degoo.com/share/o41Axz4FYFHBx7
and here is codes ---
mainActivity ---
BottomNavigationView bottomNavigationView = findViewById(R.id.main_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.main_frame_layout, new HomeFragment()).commit();
}
BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selecrFlag = null;
switch (menuItem.getItemId())
{
case R.id.nav_home:
selecrFlag = new HomeFragment();
break;
case R.id.nav_wallet:
selecrFlag = new WalletFragment();
break;
case R.id.nav_Account:
selecrFlag = new AccountFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.main_frame_layout, selecrFlag).commit();
return true;
}
};
};
Account_fragment ---
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_account, container, false);
EmailID = v.findViewById(R.id.editTextEmail);
Passwd = v.findViewById(R.id.editPassword);
SignUpBt = v.findViewById(R.id.signbutton);
LoginBt = v.findViewById(R.id.loginbutton);
LoginBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(AccountFragment.this.getContext(),AfterLogin.class));
}
});
afterlogin Fragment --
package com.thechamp.earnbyads;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class AfterLogin extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
}
}
Look like you are confused. the way that you move to another Screen is not Fragment. It is Activity.
There are many ways to deal with this.
you can change your AfterLogin to Fragment.
or implement the AfterLogin Activity as what you implement in your Current Activity that has those 3 Fragments.
I have a bottom navigation bar with multiple elements that send me to different fragments .
bottomNavigationView.setOnNavigationItemSelectedListener
(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_pokemon_description:
selectedFragment = PokemonDescriptionFragment.newInstance(MainActivity.getSelectedPokemon().get_id());
break;
case R.id.navigation_pokemon_evolutions:
selectedFragment = PokemonEvolutionsFragment.newInstance();
break;
case R.id.navigation_pokemon_moves:
selectedFragment = PokemonMovesFragment.newInstance();
break;
case R.id.navigation_pokemon_breeding:
selectedFragment = PokemonBreedingTrainingFragment.newInstance();
break;
case R.id.navigation_pokemon_location:
selectedFragment = PokemonLocationFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.commit();
return true;
}
});
All the fragments works fine except the Moves fragment , when I press it , it costs around 3 seconds to load the data and display the fragment .
I would like to show the fragment first and then , load the moves and show a progress bar or something like that while the data is loading .
This is my fragment :
public class PokemonMovesFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseAccess = DatabaseAccess.getInstance(getContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pokemon_moves, container, false);
this.view=view;
initalizeAllComponents();
initializePokemonData();
initializePostDataPopulationComponents();
getActivity().setTitle(getResources().getText(R.string.moves)+ " (" +selectedPokemon.getName() + ")");
return view;
}
//The rest of the methods
Simply move all your logic inside onViewCreated, then show Progressbar before the logic and hide Progressbar after the logic
#Override
public View onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState)
progressBar.visibility = View.VISIBLE; // Show Progress bar here
initalizeAllComponents();
initializePokemonData();
initializePostDataPopulationComponents();
getActivity().setTitle(getResources().getText(R.string.moves)+ " (" +selectedPokemon.getName() + ")");
progressBar.visibility = View.INVISIBLE; // Hide Progress bar here
}
I have a navigation drawer activity with fragments and I will send each fragment to an activity. I have a problem if I select option 3 of my menu that is a fragment that will send me to an activity, but when I return with the Back button, it sends me to option 1, what I want is that I return to option 3.
How can I change this?
I tried to do it by parentActivity but it did not work
Thank you.
My navigation drawer activitywithfragments
When I click on the button, it sends me to an activity that is this
And in the activity I have a toolbar to return and what I want is to return to option 3 and not to 1.
What do I need to do in my code or what can I place?
My fragment code option 3
public class Mis_Aliados extends Fragment {
Button boton;
public Mis_Aliados() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.persona_mi_perfil, container, false);
boton=view.findViewById(R.id.buton);
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ActividadEx.class);
startActivity(intent);
}
});
return view;
}
}
My activity code
public class ActividadEx extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pruebaactividad);
Toolbar toolbarback=findViewById(R.id.include);
setSupportActionBar(toolbarback);
getSupportActionBar().setTitle("Activity");
ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
In your ActividadEx add this method to handle toolbar back button press
I'm putting 1 intent extra to make sure you want to open Option 3 when you are back to Navigation drawer Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, NavgationDrawerActivity.class);
intent.putExtra("openOption3", true);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
On NavigationDrawerActivty inside onCreate()
you can check if Bundle has data or not. If its empty you can open Option1 fragment.
If it has data check it. and open Option3 Fragment.
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
if (bundle.getBoolean("openOption3", false)) {
//Use Fragment Transaction to Open Option 3 Fragment
} else {
//Open Option 1 Fragment Or any other Fragment
}
} else {
//Open Option 1 Fragment Or any other Fragment
}
Feel free to comment if you've any queries.
I added a refresh button to action-bar. When fragment loading that refresh button is creating in the action-bar. I have more than one fragment in my application, problem is when move between fragments and go back using back button using back button, action bar menu refresh button drawing several times. like this
following code I'm using
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_seebo_tv, container, false);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.seebo_tv, menu);
}
in main activity
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.action_refresh:
fragment=new ProgressFragment();
FragmentManager fragmentManagerProgress = getFragmentManager();
fragmentManagerProgress.beginTransaction().replace(R.id.container, fragment).addToBackStack(null).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
how can I fix this?
Try moving the call to setHasOptionsMenu(true); from onCreateView to onCreate instead.
Here's an example of a fragment adding a menu item: https://stackoverflow.com/a/31935887/798464
I have a drawer activity and a method that calls several fragments, when I select an option shows me a listview with buttons. Clicking a button sends me to a new activity that has a back button. I want to return to the previous screen, return to the option you select in the drawer activity.
public class DrawerOpcionesActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_menu);
....
drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
mostrarFragment(position);
adapterOpciones.setPositionCheked(position);
}
});
if(savedInstanceState == null){
mostrarFragment(0);
}
...
}
private void mostrarFragment(int position){
Fragment fragment = null;
System.out.println("opcion: " + position);
switch (position) {
case 1:
fragment = new LineasTransporteFragment();
break;
....
}
In the other activity...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.xxxxx);
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
... //new Intent.. I dont Know who call the save option from activity drawerOptions
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I need to save the selected option, when I call a new Intent show me the selected option. I show the fragment of default position 0
You may use SharedPrefrence of android to save the state and access back the state. Please have a look for sharedPrefrence