I have an activity, and a bunch of fragments in it. The fragments are not transitioned by sliding, but by button click. I'm trying to build a tab indicator like the one in the bottom that shows which fragment the user is. I don't even know how it's called.
This is my main Activity where all the fragments belong, and with the actionbar menu the user navigates throught the fragments. In the activity it's switched straight to the first fragment out of 4 fragments (DetailsFragment)
public class CreateWorkoutActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_workout);
DetailsFragment fragment = new DetailsFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.create_activity_frameLayout, fragment)
.addToBackStack(null)
.commit();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
}
return true;
}
return false;
}
image example
as i cannot see your code, I have this to offer https://guides.codepath.com/android/ViewPager-with-FragmentPagerAdapter ... refer this
Related
I have added three menus in BottomNavigationLayout
How can I open Center menu by default on startup?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
loadFragment(new ProfileFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
I used this to load the fragment and it also loads fragment associated with the center menu but on bottom navigation the first menu is selected.
I hope you understand my problem. if not then check the Clash Royale. in this game, the battle layout is the first pop-up at startup as well as battle menu selected in the bottom navigation.
If anyone knows how to do this please help me.
thanks in advance
Just Go for This mate ! Just Copy and paste in your editor and there you go!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
// loadFragment(new ProfileFragment()); Removed this line
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
// Added this line
navigation.setSelectedItemId(bottomNavigation.getMenu().getItem(1).getItemId());
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
Inside onCreate() method call that fragment which you want to open first at time of app launching.
When you tap on bottom menus you are performing some action for change the color of menu with fragment, Put that fragment on onCreate of the Activity with actions, So when by default when app launches it will show you your desired fragment.
Here is reference :
HomeFragment homeFragment = new HomeFragment().newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, homeFragment)
.commit();
Full Code Here :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
loadFragment(new ProfileFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
HomeFragment homeFragment = new HomeFragment().newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, homeFragment)
.commit();
}
add this in your Mainactivity
navigation.setSelectedItemId(R.id.navigation_notifications); // Pass your menu id which you want to selected first
Set your mid tab as selected item
bottomNavigationView.setSelectedItemId(R.id.tab2);
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.tab1:
loadFragment(new ProfileFragment1());
return true;
case R.id.tab2:
loadFragment(new ProfileFragment2());
return true;
case R.id.tab3:
loadFragment(new ProfileFragment3());
return true;
}
return false;
}
};
There are many questions like this asked but everything I have tried seems to not work.
Essentially I have a main activity that calls different fragments depending on what the user clicks with the home fragment being default.
I would like to have a back button on the title bar, to go back to the previous fragment.
My fragment is called from the main activity like so:
Fragment fragment = null;
fragment = new nextFragment();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment).addToBackStack(null);
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
But since ActionBarActivity activity is deprecated I need to extend AppCompatActivity instead of FragmentActivity so I can use actionbar (I'm assuming this is what I need).
However then I am unable to switch to my fragment. So does anyone know how I could implement a back button in my fragment or how to use AppCompatActivity in this situation.
Thanks for any help.
Please try this if you extend AppCompatActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Include these 2 lines ONLY if need to use Toolbar from layout xml as Action Bar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Add back navigation in the title bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//
//Other works to be done in onCreate.....
//
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
//Title bar back press triggers onBackPressed()
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
//Both navigation bar back press and title bar back press will trigger this method
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ) {
getFragmentManager().popBackStack();
}
else {
super.onBackPressed();
}
}
}
To add Back Button in title bar, you must add the following code to your Fragment.
Toolbar toolbar = (Toolbar)view.findViewById(R.id.app_bar);
AppCompatActivity AppCompatActivity = (AppCompatActivity)getActivity();
AppCompatActivity.setSupportActionBar(toolbar);
AppCompatActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
return view;
}
Don't forget to extend your MainActivity to AppCompatActivity.
You must then use this Java code in my Fragment class to react to the user tapping the back/up icon in the action bar.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActivity().onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You've saved the last fragment used by calling
addToBacktack(null).commit()
So the next step forward to call it is by overriding onBackPressed() in the activity hosting the fragment.
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
}
else {
super.onBackPressed();
}
}
So whenever you call the activity's onBackPressed() from the fragment, the fragment would go back to the last saved fragment.
I have Base Activity including NavigationView with 2 menu items. On start it loads Home fragment having background image inside it. Each loads specific fragment. When I select Terms & Conditions menu item, it loads T&C fragment & when I press back button it simply kills it.
However, when I select About Us menu item, it loads About Us fragment but I need to press BACK button twice to kill it. I need to know why does it happen?
Part of Code in AppBaseActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
HomeFragment homeFragment = new HomeFragment();
fragmentTransaction.add(R.id.body_container, homeFragment, "");
fragmentTransaction.commit();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
navigationView.getMenu().findItem(item.getItemId()).setChecked(true);
switch (item.getItemId()) {
case R.id.nav_terms :
fragmentTransaction = fragmentManager.beginTransaction();
TCFragment tcFragment = new TCFragment();
fragmentTransaction.replace(R.id.body_container, tcFragment, "");
fragmentTransaction.commit();
break;
case R.id.nav_about_us :
fragmentTransaction = fragmentManager.beginTransaction();
AboutUsFragment aboutUsFragment = new AboutUsFragment();
fragmentTransaction.replace(R.id.body_container, aboutUsFragment, "");
fragmentTransaction.commit();
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
All fragments simply have overridden onCreateView() by inflating respected xml only. No code is written in both fragments yet.
You can stop back hardware navigation if you want.
Simply using onBackPressed() without super.onBackPressed()
#Override
public void onBackPressed() {
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
In a Bluetooth-related app (with minSdkVersion="18") I have a single MainActivity.java, displaying one of the following 3 UI Fragments:
MainFragment.java (the top screen)
SettingsFragment.java (settings screen, entered through menu)
ScanningFragment.java (lists nearby Bluetooth devices)
To display an "Up button" and handle the "Back button" I have the following code in place:
public class MainActivity extends Activity
implements BleWrapperUiCallbacks {
// set in onResume() of each fragment
private Fragment mActiveFragment = null;
ยด #Override
public void onBackPressed() {
if (!getFragmentManager().popBackStackImmediate())
super.onBackPressed();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_root);
getActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
Fragment fragment = new MainFragment();
getFragmentManager().beginTransaction()
.replace(R.id.root, fragment, "main")
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStackImmediate();
break;
case R.id.action_settings:
Fragment fragment = new SettingsFragment();
getFragmentManager().beginTransaction()
.addToBackStack(null)
.replace(R.id.root, fragment, "settings")
.commit();
break;
}
return super.onOptionsItemSelected(item);
}
This works well, but has a cosmetic problem, that the "Up button" is still displayed when the MainFragment.java is being displayed - as you can see on the left side of the above screenshot.
I have tried calling
getActionBar().setHomeButtonEnabled(false);
when that fragment is being active, but that only disables the "Up button" - without really hiding it.
With help of Little Child (thanks!) here my solution using the FragmentManager.OnBackStackChangedListener:
public class MainActivity extends Activity
implements OnBackStackChangedListener,
BleWrapperUiCallbacks {
#Override
public void onCreate(Bundle savedInstanceState) {
...
getFragmentManager().addOnBackStackChangedListener(this);
}
#Override
public void onBackStackChanged() {
getActionBar().setDisplayHomeAsUpEnabled(
getFragmentManager().getBackStackEntryCount() > 0);
}
You are in luck because in API level 18 there is this:
getActionBar().setHomeAsUpIndicator(R.drawable.ic_yourindicator);
for support library, it is:
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_yourindicator);
So now depending upon what fragment you are in, you can change the icon of "up" button.
Also, try this:
getActionBar().setDisplayHomeAsUpEnabled(false);
Set whether home should be displayed as an "up" affordance.
2021 Working Solution:
(requireActivity() as AppCompatActivity).supportActionBar?.setHomeAsUpIndicator(null)
I have a main activity in which I designate tabs using three fragments. I have a button on the ActionBar which navigates to a different fragment say "Info about the app" Once user navigates to this particular fragment (Info) I disable it so that it is not called again and again. Then on the back key in the main activity I re-enable it. So far so good. But I am not able to re-enable it for one scenario: Say if user navigates to the info fragment and does not press back, but however if he navigates to a different tab, the info button is still disabled because back-press has not been called. I tried a lot of things in onStart() and onResume() of fragments but I am not able to reference the menuItem in any of those as I get a null pointer.
Code Reference: (MainActivity while calling the info fragment from onOptionsSelected):
public boolean onOptionsItemSelected(MenuItem item) {
mMenuItem = item;
switch (item.getItemId()) {
case R.id.info:
Tab d = getActionBar().getSelectedTab();
System.out.println(""+d.getText().toString());
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
String a = d.getText().toString();
if(a.equalsIgnoreCase("Reminders")){
FragmentContact fragmentcontact = new FragmentContact();
fragmentTransaction.replace(R.id.realtabcontent, fragmentcontact);
mMenuItem.setEnabled(false);
//mMenuItem.setIcon(R.drawable.btn_age_01);
}
else if(a.equalsIgnoreCase("Notifications")){
FragmentContact fragmentcontact = new FragmentContact();
fragmentTransaction.replace(R.id.realtabcontent2, fragmentcontact);
mMenuItem.setEnabled(false);
}
else if(a.equalsIgnoreCase("Contacts")){
FragmentContact fragmentcontact = new FragmentContact();
fragmentTransaction.replace(R.id.realtabcontent3, fragmentcontact);
mMenuItem.setEnabled(false);
}
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
break;
on Back key(Main Activity):
#Override
public void onBackPressed() {
mMenuItem.setEnabled(true);
super.onBackPressed();
}
The solution was very simple, to set an options menu for individual "Fragments" use:
setHasOptionsMenu(true);
Cheers!!