My app has preference headers on which you choose what fragment to start. After you are in some fragment I want that click on back button shows header again and if I press back again when headers are shown to return me to some other activity.
I overridded onOptionsItemSelected in Activity and in Fragment but it always calls action from activity because I am trying to bind fragment and activity to same action. Here is my code:
public class SettingsActivity extends AppCompatPreferenceActivity {
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preference_headers, target);
}
#Override
protected boolean isValidFragment(String fragmentName) {
return SettingsFragment.class.getName().equals(fragmentName);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.app_preferences);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
I managed to solve this by removing onOptionsItemSelected method from activity and leave inside fragment. Now when I press up inside fragment it goes to SettingsActivity and when up is pressed inside activity it acts like onBackPressed(). Hope this helps somebody.
I am a newbie to Android development. I am learning UI designing as of now. I want a solution where there is a bottom bar with 5 options linked directly to 5 different activities. I got Java solutions from other stack overflow answers (How to change activity on bottom navigation button click? ) - 2nd Answer by sushil, but it has no activity - XML files in it for me to understand.
Bottom bar like this:
Activity to be loaded based on bottom bar:
As per your attached image, you should used Fragment instead of Activity for 5 different MenuItem or options to achieve your desired output.
1. Create 5 different Fragments for 5 different MenuItem.
For example: MatchingFragment, WatchListFragment, RatesFragment, DealsFragment and ListingFragment.
2. Add OnNavigationItemSelectedListener to your NavigationView and change Fragment as per your selected MenuItem. Use below code to change Fragment:
// Set action to perform when any menu-item is selected.
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Change Fragment
selectFragment(item);
return false;
}
});
/**
* Perform action when any item is selected.
*
* #param item Item that is selected.
*/
protected void selectFragment(MenuItem item) {
item.setChecked(true);
switch (item.getItemId()) {
case R.id.action_matching:
// Action to perform when Matching Menu item is selected.
pushFragment(new MatchingFragment());
break;
case R.id.action_watch_list:
// Action to perform when WatchList Menu item is selected.
pushFragment(new WatchListFragment());
break;
case R.id.action_rates:
// Action to perform when Rates Menu item is selected.
pushFragment(new RatesFragment());
break;
case R.id.action_deals:
// Action to perform when Deals Menu item is selected.
pushFragment(new DealsFragment());
break;
case R.id.action_listing:
// Action to perform when Listing Menu item is selected.
pushFragment(new ListingFragment());
break;
}
}
/**
* Method to push any fragment into given id.
*
* #param fragment An instance of Fragment to show into the given id.
*/
protected void pushFragment(Fragment fragment) {
if (fragment == null)
return;
FragmentManager fragmentManager = getFragmentManager();
if (fragmentManager != null) {
FragmentTransaction ft = fragmentManager.beginTransaction();
if (ft != null) {
ft.replace(R.id.rootLayout, fragment);
ft.commit();
}
}
}
Here is the complete Tutorial: Android Bottom Navigation View Tutorial With Example
Hope this will help~
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorites:
Intent intent1 = new Intent(this, AnActivity.class);
startActivity(intent1);
break;
case R.id.action_schedules:
Intent intent2 = new Intent(this, AnotherActivity.class);
startActivity(intent2);
break;
case R.id.action_music:
Intent intent3 = new Intent(this, AnotherActivity.class);
startActivity(intent3);
break;
}
return true;
}
});
Base Activity :
public abstract class BaseActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
protected BottomNavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId());
navigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
navigationView.setOnNavigationItemSelectedListener(this);
}
#Override
protected void onStart() {
super.onStart();
updateNavigationBarState();
}
// Remove inter-activity transition to avoid screen tossing on tapping bottom navigation items
#Override
public void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
navigationView.postDelayed(() -> {
int itemId = item.getItemId();
if (itemId == R.id.navigation_analysis) {
startActivity(new Intent(getApplicationContext(), AnalysisActivity.class));
} else if (itemId == R.id.navigation_dashboard) {
startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
} else if (itemId == R.id.navigation_profile) {
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}
finish();
}, 100);
return true;
}
private void updateNavigationBarState(){
int actionId = getNavigationMenuItemId();
selectBottomNavigationBarItem(actionId);
}
void selectBottomNavigationBarItem(int itemId) {
Menu menu = navigationView.getMenu();
for (int i = 0, size = menu.size(); i < size; i++) {
MenuItem item = menu.getItem(i);
boolean shouldBeChecked = item.getItemId() == itemId;
if (shouldBeChecked) {
item.setChecked(true);
break;
}
}
}
abstract int getContentViewId();
abstract int getNavigationMenuItemId();
}
Make sure to use getApplicationContext in onNavigationSelected().
Dashboard Activity:
public class DashboardActivity extends BaseActivity {
#Override
int getContentViewId() {
return R.layout.activity_dashboard ;
}
#Override
int getNavigationMenuItemId() {
return R.id.navigation_dashboard;
} }
Similarly - make the other activities just like this.
XML PART
bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.BottomNavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:menu="#menu/navigation"
/>
navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_analysis"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/title_analysis" />
<item
android:id="#+id/navigation_dashboard"
android:icon="#drawable/ic_dashboard_black_24dp"
android:title="#string/title_dashboard" />
<item
android:id="#+id/navigation_profile"
android:icon="#drawable/ic_notifications_black_24dp"
android:title="#string/title_profile" />
</menu>
activity_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/frame_dashboard">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/title_dashboard"/>
</FrameLayout>
<include
layout="#layout/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
/>
</LinearLayout>
Similarly - make other xml files just like this.
This should hopefully help
I have the following Activity code:-
public class legislator_info extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_legislator_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Legislator Info");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
String bioguide = i.getExtras().getString("Person");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// click on 'up' button in the action bar, handle it here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
So basically I have a fragment which has a list view displayed in it. On click of a list Item I start this activity and I want to go back to the previous fragment on the back button click. I tried the above code but I am not able to travel back. Am pretty new at this any help is appreciated.
I have added my fragment in the following way:-
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
LegislatorFragment lf = new LegislatorFragment();
ft.replace(R.id.fragment_container,lf);
ft.addToBackStack(null);
ft.commit();
I am still not clear what you want to achieve but you can try this
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
EDIT:
case android.R.id.home:
//call onBackPressed here
onBackPressed();
return true;
You have to override onOptionsItemSelected because you are trying with Action bar's back button.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
Then override BackPressed -
#Override
public void onBackPressed()
{
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
}
else {
super.onBackPressed();
}
}
with the help of these Android Docs.I am trying to do a action bar Back button.I get an Action Bar Back Button like these below image:
Output:
But My problem is After watching the Gallery images I press the action bar back button.
Then it is not working.But it have to go back to previous page.
Listed below are the codings.
GalleryActivity.java:
import android.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import com.fth.android.R;
public class GalleryActivity extends FragmentActivity {
private int position;
private static String id;
private static String name;
private DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
position = getIntent().getExtras().getInt("position");
id = getIntent().getExtras().getString("id");
name = getIntent().getExtras().getString("name");
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME|ActionBar.DISPLAY_USE_LOGO|ActionBar.DISPLAY_HOME_AS_UP);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent upIntent = new Intent(this, HomeActivity.class);
upIntent.putExtra("position", position);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
TaskStackBuilder.from(this)
.addNextIntent(upIntent)
.startActivities();
finish();
} else {
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
GalleryDetailFragment.java:
import com.sit.fth.model.GalleryDetail;
import com.sit.fth.util.APIServiceHandler;
import com.sit.fth.util.AppConstants;
import com.sit.fth.util.AppPromoPager;
public class GalleryDetailFragment extends BaseFragment implements
PromoPagerListener {
private TextView countView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.setHasOptionsMenu(true);
id = getArguments().getString("id");
name = getArguments().getString("name");
View view = inflater.inflate(R.layout.app_pager, null);
return view;
}
}
Anybody can help me if you know how to solve these.Thank You.
I solved these problem by adding the below coding in GalleryActivity.
ActionBar actionBar;
actionBar=getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
In MainActivity:
Previously,
public class HomeActivity extends BaseActivity
Then I change into
public class HomeActivity extends FragmentActivity
In GalleryFragment:
I use Intent to pass it to the GalleryActivity.
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Gallery gallery = (Gallery) arg0.getAdapter().getItem(arg2);
Intent intent = new Intent(getActivity(), GalleryActivity.class);
intent.putExtra("position", position);
intent.putExtra("id", gallery.getGalId());
intent.putExtra("name", gallery.getAlbumTitle());
startActivity(intent);
// mCallback.OnGalItemSelected(gallery.getGalId(),gallery.getAlbumTitle());
}
Please read this
you should have something like this:
<activity
android:name="com.sit.fth.activity.HomeActivity"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.sit.fth.activity.GalleryActivity"
android:screenOrientation="portrait"
android:parentActivityName="com.sit.fth.activity.HomeActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.sit.fth.activity.HomeActivity"/>
</activity>
then calling NavUtils.navigateUpFromSameTask(this) will cause navigating to parent activity (HomeActivity).
You need to call setDisplayHomeAsUpEnabled(true) method in the onCreate method and override onSupportNavigateUp() and call onBackPressed() in it as below. That's it. done :)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
You have just to add the following line to the activity in the manifest.xml. The parent activity is the activity to which you want to go back.
android:parentActivityName=".activities.MainActivity"
Try like
First of all you need to use addToBackStack() before commit() for Fragments
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
if(getSupportFragmentManager().getBackStackEntryCount()>0)
getSupportFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
Best and easy answer is add the parent activity name in Manifest file, so Actionbar back button will work.
For that under that Activity tag of Manifest File use
android:parentActivityName=".MyCustomParentActivity"
if the home button is shown. you should add an action to the home button through onOptionItemSelected fun (arrow in your case) by default there's no action. so it's totally normal that it's not working. Please add this fun to your activity :
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when {
item.itemId == android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
None of the answers provided here worked for me. I had to put the switch inside the onMenuItemSelected method. I'm aware this is not what is stated in the Android documentation, but still, it worked, so I just thought I'd leave this here for people who run into the same issue. My problem involved an Activity instead of a Fragment though, but that should be pretty much the same.
class FooActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return false;
}
}
To me, I had to set mDrawerToggle.setToolbarNavigationClickListener(...) to a listener that triggers the back action. Otherwise it does nothing. This is what the source code of ActionBarDrawerToggle looks like:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mDrawerIndicatorEnabled) {
toggle();
} else if (mToolbarNavigationClickListener != null) {
mToolbarNavigationClickListener.onClick(v);
}
}
});
So the default behaviour is actually to call our listener, and not do any magic on its own.
Use on SupportNavigateUp() method and call onBackPressed in this method.
onCreate
{
...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
...
}
public void resetActionBar()
{
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
int count = fm.getBackStackEntryCount();
if(count == 0) {
// Do you want to close app?
showDialog();
}else{
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Log.i("coming", "comming");
//noinspection SimplifiableIfStatement
if(id==android.R.id.home){
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
Here is one more thing to check for in case the other answers here (or here or here or here) don't work.
I had copied some code from another activity that disabled the menu. Deleting this method (and applying the solutions given in the others answers) allowed the up button to work.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// hide the menu
return false;
}
In my case I had overridden the onCreateOptionsMenu method and I forgot to call super at the end.
Tool bar enable back button for Kotlin binding
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_times_ic)
I'm opening a SherlockActivity coming from a SherlockFragment.
Now I want to build an Actionbar with a back button. That works:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
But how can I go back to my Sherlockfragment? This does not work. The error code is "unable to find explicit activity class"
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
return true;
default:
// This do NOT bring me back to my SherlockFragment !!! //
Intent in = new Intent(this, MySherlockFragment.class);
startActivity(in);
return super.onOptionsItemSelected(item);
}
}
How can I start my Sherlockfragment out of my SherlockActivity?
Thank you :-)