We often see Settings screen in many android apps through which you can configure the app preferences on your choice. For example you wanna change the notification sound or turn off notification messages from the app settings.
Normally people manually develop their own UI for settings and manage the values in shared preferences, not awaring the fact that android do provide APIs specific to Settings Preferences to achieve the same in a robust way. In this article we are going to learn how to implement the settings screen considering the various combinations of settings items.
The preference API consists of multiple widget like EditTextPreference, CheckBoxPreference, ListPreference and few more to achieve the most used settings. You can also implement the advanced options like ringtone selection, sync options etc.,
1. Settings with Preference Headers
Preference Headers displays only the settings groups (headers) on the first screen and selecting a group displays the sublist. The preference headers usually used for tablets or if there are multiple settings with nested options. The benefit of using headers is, the screen will be automatically divided into two panels when the app is running on tablet.
Below is the example of Youtube app settings with preference headers.
1.1 Adding Settings Activity from Android Studio Templates
The Settings Activity can be added from Android Studio templates directly with all the necessary code added to activity.
In Android Studio go to File ⇒ Activity ⇒ Settings Activity. This creates necessary preferences xml resources under res ⇒ xml directory.
If you launch the Settings Activity, you will see the output as below.
The Problem:
The problem with creating settings from a template is, there is no guarantee that the auto generated code always meets your requirements. With current version of Android Studio I have (v2.3), the settings activity is generated with all headers as default screen which is not necessary in my app. Even it takes more effort to customize the auto generated code. The best way is, create everything manually so that you will have more control over the output you are expecting.
So let’s start by creating new project in Android Studio and see how to add the settings manually.
2. Creating New Project
1. Create a new project in Android Studio from File ⇒ New Project and fill the project details. I gave project name as Preferences and package name as info.androidhive.settings.
2. Open strings.xml and add the below string values.
<resources> <string name="app_name">Preferences</string> <string name="action_settings">Settings</string> <string name="title_activity_settings">Settings</string> <string name="pref_title_ringtone">Ringtone</string> <string name="pref_ringtone_silent">Silent</string> <string name="default_gallery_storage">My Videos</string> <string name="title_auto_upload">Auto upload</string> <string name="summary_upload_over_wifi">Upload the videos when wifi is available</string> <string name="title_upload_quality">Upload Quality</string> <string name="summary_upload_video_quality">Specify video quality for uploads</string> <string name="pref_title_notifications">Notifications</string> <string name="summary_choose_ringtone">Choose notification sound</string> <string name="pref_header_about">About</string> <string name="summary_about">We are a team of like-minded people, specialized in development of Android App Development creating new trends across the app space. Glad to Help in anyway!</string> <string name="app_version">3.5</string> <string name="summary_support">Got any queries? We are happy to help!</string> <string name="title_send_feedback">Send Feedback</string> <string name="title_faq">FAQ</string> <string name="summary_faq">View frequently asked questions</string> <string name="url_faq">https://www.androidhive.info/privacy-policy/</string> <string name="privacy_policy">Privacy Policy</string> <string name="url_privacy">https://www.androidhive.info/privacy-policy/</string> <string name="title_terms">Terms & Conditions</string> <string name="url_terms">https://www.androidhive.info/terms-of-service/</string> <string name="title_version">Version</string> <string name="choose_email_client">Choose email client</string> <string name="title_gallery_storage">Default Storage</string> <string name="title_new_notification_sound">New message notification</string> <string name="title_vibrate">Vibrate</string> <string name="summary_vibrate">Vibrate on new notification</string> <string name="key_upload_over_wifi">key_upload_over_wifi</string> <string name="key_gallery_name">key_gallery_name</string> <string name="key_upload_quality">key_upload_quality</string> <string name="notifications_new_message">notifications_new_message</string> <string name="key_notifications_new_message_ringtone">key_notifications_new_message_ringtone</string> <string name="key_vibrate">key_vibrate</string> <string name="key_send_feedback">key_send_feedback</string> </resources>
3. Create new xml named arrays.xml under res ⇒ arrays.xml and add the below arrays. These arrays contains values necessary for ListPrefereces.
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="pref_upload_quality_entries"> <item>360p</item> <item>480p</item> <item>720p</item> <item>1080p</item> <item>Original</item> </string-array> <string-array name="pref_upload_quality_values"> <item>0</item> <item>1</item> <item>2</item> <item>3</item> <item>4</item> </string-array> </resources>
4. Create an xml named pref_main.xml under res ⇒ xml. If the xml directory is not existed, create a new folder with the name.
The preferences screen can be designed with an xml just like the layout xml we use for a view, except it will reside in xml directory. We have used below elements in the current settings screen.
> EditTextPreference – Used to collect text input from user
> CheckBoxPreference – Displays a checkbox to toggle a setting
> ListPreference – Displays a diglog with list of options to choose
> SwitchPreference – Turn on/off a setting
> RingtonePreference – Launches devices’s ringtone list in which user can select preferred sound
> Preference with an Intent action android.intent.action.VIEW – to open external browser navigating to an url
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="General"> <EditTextPreference android:defaultValue="@string/default_gallery_storage" android:key="@string/key_gallery_name" android:summary="@string/default_gallery_storage" android:title="@string/title_gallery_storage" /> <CheckBoxPreference android:defaultValue="true" android:key="@string/key_upload_over_wifi" android:summary="@string/summary_upload_over_wifi" android:title="@string/title_auto_upload" /> <ListPreference android:defaultValue="3" android:dialogTitle="@string/title_upload_quality" android:entries="@array/pref_upload_quality_entries" android:entryValues="@array/pref_upload_quality_values" android:key="@string/key_upload_quality" android:summary="@string/summary_upload_video_quality" android:title="@string/title_upload_quality" /> </PreferenceCategory> <PreferenceCategory android:title="@string/pref_title_notifications"> <SwitchPreference android:defaultValue="true" android:key="@string/notifications_new_message" android:title="@string/title_new_notification_sound" /> <RingtonePreference android:defaultValue="content://settings/system/notification_sound" android:dependency="notifications_new_message" android:key="@string/key_notifications_new_message_ringtone" android:ringtoneType="notification" android:summary="@string/summary_choose_ringtone" android:title="@string/pref_title_ringtone" /> <SwitchPreference android:defaultValue="true" android:key="@string/key_vibrate" android:summary="@string/summary_vibrate" android:title="@string/title_vibrate" /> </PreferenceCategory> <PreferenceCategory android:title="@string/pref_header_about"> <Preference android:selectable="false" android:summary="@string/summary_about" /> <Preference android:summary="@string/app_version" android:title="@string/title_version" /> <Preference android:key="@string/key_send_feedback" android:summary="@string/summary_support" android:title="@string/title_send_feedback" /> <!-- preference opens url in browser --> <Preference android:summary="@string/summary_faq" android:title="@string/title_faq"> <intent android:action="android.intent.action.VIEW" android:data="@string/url_faq" /> </Preference> <Preference android:title="@string/privacy_policy"> <intent android:action="android.intent.action.VIEW" android:data="@string/url_privacy" /> </Preference> <Preference android:title="@string/title_terms"> <intent android:action="android.intent.action.VIEW" android:data="@string/url_terms" /> </Preference> </PreferenceCategory> </PreferenceScreen>
5. Create a class named AppCompatPreferenceActivity.java and add the below code. This class provides compatibility across all the devices and versions.
import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceActivity; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatDelegate; import android.support.v7.widget.Toolbar; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; /** * A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls * to be used with AppCompat. */ public abstract class AppCompatPreferenceActivity extends PreferenceActivity { private AppCompatDelegate mDelegate; @Override protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getDelegate().onPostCreate(savedInstanceState); } public ActionBar getSupportActionBar() { return getDelegate().getSupportActionBar(); } public void setSupportActionBar(@Nullable Toolbar toolbar) { getDelegate().setSupportActionBar(toolbar); } @Override public MenuInflater getMenuInflater() { return getDelegate().getMenuInflater(); } @Override public void setContentView(@LayoutRes int layoutResID) { getDelegate().setContentView(layoutResID); } @Override public void setContentView(View view) { getDelegate().setContentView(view); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { getDelegate().setContentView(view, params); } @Override public void addContentView(View view, ViewGroup.LayoutParams params) { getDelegate().addContentView(view, params); } @Override protected void onPostResume() { super.onPostResume(); getDelegate().onPostResume(); } @Override protected void onTitleChanged(CharSequence title, int color) { super.onTitleChanged(title, color); getDelegate().setTitle(title); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getDelegate().onConfigurationChanged(newConfig); } @Override protected void onStop() { super.onStop(); getDelegate().onStop(); } @Override protected void onDestroy() { super.onDestroy(); getDelegate().onDestroy(); } public void invalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } private AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, null); } return mDelegate; } }
6. Create new activity named SettingsActivity from File ⇒ New ⇒ Activity ⇒ Empty Activity and do the below changes.
> Extend this class from AppCompatPreferenceActivity that we have created in the above step.
> Remove setContentView() and load the MainPreferenceFragment() fragment.
> MainPreferenceFragment() contains all the necessary methods to inflate the settings xml, provides callbacks when the settings are changed.
package info.androidhive.settings; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.preference.RingtonePreference; import android.text.TextUtils; import android.view.MenuItem; public class SettingsPrefActivity extends AppCompatPreferenceActivity { private static final String TAG = SettingsPrefActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // load settings fragment getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit(); } public static class MainPreferenceFragment extends PreferenceFragment { @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_main); // gallery EditText change listener bindPreferenceSummaryToValue(findPreference(getString(R.string.key_gallery_name))); // notification preference change listener bindPreferenceSummaryToValue(findPreference(getString(R.string.key_notifications_new_message_ringtone))); // feedback preference click listener Preference myPref = findPreference(getString(R.string.key_send_feedback)); myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { sendFeedback(getActivity()); return true; } }); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return super.onOptionsItemSelected(item); } private static void bindPreferenceSummaryToValue(Preference preference) { preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String stringValue = newValue.toString(); if (preference instanceof ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); // Set the summary to reflect the new value. preference.setSummary( index >= 0 ? listPreference.getEntries()[index] : null); } else if (preference instanceof RingtonePreference) { // For ringtone preferences, look up the correct display value // using RingtoneManager. if (TextUtils.isEmpty(stringValue)) { // Empty values correspond to 'silent' (no ringtone). preference.setSummary(R.string.pref_ringtone_silent); } else { Ringtone ringtone = RingtoneManager.getRingtone( preference.getContext(), Uri.parse(stringValue)); if (ringtone == null) { // Clear the summary if there was a lookup error. preference.setSummary(R.string.summary_choose_ringtone); } else { // Set the summary to reflect the new ringtone display // name. String name = ringtone.getTitle(preference.getContext()); preference.setSummary(name); } } } else if (preference instanceof EditTextPreference) { if (preference.getKey().equals("key_gallery_name")) { // update the changed gallery name to summary filed preference.setSummary(stringValue); } } else { preference.setSummary(stringValue); } return true; } }; /** * Email client intent to send support mail * Appends the necessary device information to email body * useful when providing support */ public static void sendFeedback(Context context) { String body = null; try { body = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; body = "\n\n-----------------------------\nPlease don't remove this information\n Device OS: Android \n Device OS version: " + Build.VERSION.RELEASE + "\n App Version: " + body + "\n Device Brand: " + Build.BRAND + "\n Device Model: " + Build.MODEL + "\n Device Manufacturer: " + Build.MANUFACTURER; } catch (PackageManager.NameNotFoundException e) { } Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"contact@androidhive.info"}); intent.putExtra(Intent.EXTRA_SUBJECT, "Query from android app"); intent.putExtra(Intent.EXTRA_TEXT, body); context.startActivity(Intent.createChooser(intent, context.getString(R.string.choose_email_client))); } }
Now we have the settings screen implemented. We just need to add a menu item in the toolbar’s overflow menu to launch the settings.
7. Open menu_main.xml under res ⇒ menu and add the settings menu item.
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="info.androidhive.settings.MainActivity"> <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="@string/action_settings" app:showAsAction="never" /> </menu>
8. Open MainActivity.java and launch SettingsActivity when the settings is selected from overflow menu.
package info.androidhive.settings; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { // launch settings activity startActivity(new Intent(MainActivity.this, SettingsPrefActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
Run the project and open the settings from toolbar’s menu item.
I hope this article explained most of the concepts regarding preference settings. If you still have any queries, please do let me know in the comments section below.
Happy Coding 😀
References
Settings developer guide
https://developer.android.com/guide/topics/ui/settings.html
Material guidelines for Settings
https://material.io/guidelines/patterns/settings.html
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
Thank you so much Ravi, your tutorials literarily makes my dev life easier
You are welcome Michael 🙂
Thank you so much for the tutorial. You have covered lot of implementation difficulties developers face in this tutorial.
Cheers!
plz sir make a tutorial of android app to make a recycle view or an array items app that when we click so a next activity open with its full image and description like a food recipe app or image gallery app with its admin panel or cms thanks
Hi Abdul
It can’t be explained in a single article. You have to learn few things and integrate them together. Try learning these
http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
http://www.androidhive.info/2016/01/android-working-with-recycler-view/
bundle of thanks for ur quick reply sir Ravi Tamada thanks
Get help from androidhive I have successfully create my new app
https://bit.ly/intervalTimerSets
Thanks Ravi
Nice tutorial ravi,
thanks a lot
out of thread question, i wonder how do you create the video mirroring the app running on the phone?
I records my mobile screen and place it on a nexus skin while editing.
Which software u use for editing videos?
DU Recorder
Hey @Ravi Tamada:disqus do you have any tutorial on writing test cases for android app?
Test Cases like JUnit or Mockito, or Instrumentation.
Or do you have any plan to do a tutorial on writing test cases?
If you have some source codes where you did these test cases as well then can you post it here or send me at gladiatorrick@gmail.com ?
How to replace the value received from EditTextPreference or ListPreference or toogle to the variable of another activity to actually implement the changes made in settings activity. Another question is:- i have toogle option in settings to toogle dark and light theme. How do i implement this theme feature?
Thanks in advance!
Extend your base theme from Theme.AppCompat.Night
Get the preference and set the theme based on it.
Check out the article below on how to set the theme
https://medium.com/@chrisbanes/appcompat-v23-2-daynight-d10f90c83e94
Also I would recommend three option in user setting like Light, Dark and Auto
Thanks Mohamed.
You are welcome mate!! BTW thanks for the awesome tutorials. I hope you would do one explaining the basics of MVVM or MVP architecture.
hello
i want to add 3 dots option in my app, how will i get it
please help
1. create menu folder under res folder, right click in res folder – new – android resource directory – resource type choose menu – ok
2. create menu_main.xml under menu folder, look at point 7 above
3. add onCreateOptionsMenu(Menu menu) and onOptionsItemSelected(MenuItem item) inside mainactivity, look at point 8 above
cmiiw
where are these 7 and 8 points???
read tutorial in this url, scroll above please then find point 7 and 8
Good tutorial Ravi
I have problem with actionBar error java.lang.NullPointerException in line getSupportActionBar().setDisplayHomeAsUpEnabled(true);
If I was deleted getSupportActionBar().setDisplayHomeAsUpEnabled(true); SettingsActivity can launch but without Toolbar, how to solved that?
Thanks in advance!
Make sure you are not extending your theme from theme.appcompat.light.noactionbar or any other noactionbar variants for your settings activity.
If you want to use your custom toolbar then you have to create a layout resource file with toolbar and FrameLayout to attach Preference fragment.
thanks Mohamed
I was try to remove extending noactionbar in manifest and on styles.xml but there’s still error NPE. I am using Theme.AppCompat.Light.DarkActionBar
Do you have example for custom toolbar?Thanks in advance!
Hi paijojr,
Theme.AppCompat.Light.DarkActionBar should have fixed it, can you post your error logs?
Also try this one and see it fixes the error
Then in your actvity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setupToolbar();
getSupportFragmentManager().beginTransaction().replace(R.id.prefFrame,
new SettingsFragment()).commit();
}
Setting Fragment Should stay the same
Hello sir
i want to add pagination like websites in my app to display history. How will i get it. Please help
is it possible?
It is. How the content is fetched from server? Is it via REST API?
yes
Eagerly waiting for your reply
Amazing Tutorial Ravi..
I want to ask how to disable and enable internet connection, Preferences Settings Screen?
I think you have to manually enable / disable Wifi or Internet on Preference Settings call back.
Refer these link
https://stackoverflow.com/questions/11555366/enable-disable-data-connection-in-android-programmatically
https://stackoverflow.com/questions/3930990/android-how-to-enable-disable-wifi-or-internet-connection-programmatically
Am having a problem I cant load the actionbar on the SettingsActivity
Whats the theme set to SettingsActivity in AndroidManifest?
I am currently using a custom theme and face the same problem.
Hey Ravi, I have problem on ‘extends AppCompatPreferenceActivity’ in SettingsActivity. Any clue?
Hi ,
I have chechBoxPrefernce within PrferenceCategory .
My requirement is to make check box true always at backend and that prefernce should be invisible from screen in mobile . How to make Preference category invisible from front end .
Suggest me .
For that you don’t need to have chechBoxPrefernce and make it visible. You can achieve the same by
the following…
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
pref = _context.getSharedPreferences(“mySharedPrefs”, PRIVATE_MODE);
editor = pref.edit();
editor.putBoolean(“key_checkbox”, true);
// commit changes
editor.commit();
Great tutorial, but backarrow in toolbar in settings with headers doesnt work. Please help me.
You need to mention parent activity in your AndroidManifest.xml or override
onOptionsItemSelected
in your activity.Add the below to your activity
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
Quick Question: does this not work for Android builds that are higher than Honeycomb? I made a settings activity, but noticed @TargetApi(Build.VERSION_CODES.HONEYCOMB) in my code.
Thanks!
how can i get edittext value in a string in mainActivity?
hello new to android development.. someone please tell me how can i get data so i can use it in my services and main activity.
example
“`
“`
get value from above to a string called mqtthost.
HI ravi would you please write some article regarding MVC pattern
Yes please make one post on mvc , i cannot find any simple explanation in web so i am not able to understand . If possible use dagger, butterknife and rxjava. Hope you will make soon . Thank you.
I have prepared a Draft but explaining it in easier way is a bit difficult because of MVP structure. I’ll write it soon.
Sir is it possible to make a notification by toggle on the switchpreference??
If yes, how??
Keep a boolean value in preference settings. Before showing the notification using notification method, check the boolean value and show the notification. Your device will always receives the notifications, but will be visible to user only when the option is enabled in preference settings.
thanks for your answer. I’ve tried it, but the showNotification() is not a static method, it could not be referenced in MainPreferenceFragment.
It has to be called from notification receiver classes. You have to check your preference value in that class instead in main activity.
when i extend appcompatpreferencesActivity this show me error unsolvable reference
what i doing wrong.
setSummary() not accept string value for ListPreference.
Please Share Us Web Service Tutorials
Here are some
https://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/
https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
https://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
Sir! Please Tell me how to set offline resources for the images.Answer would be apperciated.Please tell me i
didn’t want online content i only want images from offline assets folder please tell me the changes that i have to do in you current code(Gallery App with Glide)
You can use the code from here. You need to port this in Adapter class.
https://stackoverflow.com/questions/7645268/how-to-load-a-image-from-assets
The notification headers are coming as single line hence ending with 2 dots(..). How to make the headers multiline. ?
Hi, how did you create that sliding animation when you click on the BACK and Settings button? The code is not presented in your above provided code. Thank you.
The arrow was shown using
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
. You can identify the click of the arrow by overridingonOptionsItemSelected
method.@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// take your action here
return true;
}
return super.onOptionsItemSelected(item);
}
I know all that.. I used the below code for when you click on Settings button and the following code does a specific animation:
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
Do I also place code for clicking BACK arrow animation, in the same “onOptionsItemsSelected(MenuItem item)” code?
Yes, you can.
Ok, I got it figured out now, thank you. Last question. I created a fragmented tab layout with various tabs. When I click from Settings the <– back button, it always takes me back to the specific tab that I came from.
Which code in your code above is the one that saves and remembers the specific tab I was on when I clicked on Settings?
For example if I was on my "Groups" tab and clicked on settings then when I clicked BACK out of settings, it'd take me back to "Groups" tab specifically and not the default 1st tab in TabLayout.
That is the default behavior of Tabs.
When I’m on my 2nd tab for example and click on the Floating Action Bar then when I click back in the Floating Action Bar pg, it takes me back to the default 1st tab and not to the 2nd tab where I was.
That’s why I’m curious which code it was to take me back to specific tab instead of the default 1st tab.
i still dont understand the sliding animation,is that view pager default animation?
Yes
Attempt to invoke virtual method ‘void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)’ on a null object reference
kindly help
You need to have Toolbar / Appbar in your activity. Either add it in your activity layout or add it via theme in manifest file.
thank you i am trying to add the settings preference on a navigation drawer facing some challenges
hello ravi sir iam a fan of yours thanks for all the tutorials….can you please post a tutorial about data binding?
First of all your tutorial was the best I found so far, it helped me a lot. Thank you. Secondly, I was testing your code and saw that when I selected a Upload Quality option the summary was not updated. Studying your code I realized that in order to correct this, I simply added in the MainPreferenceFragment’s onCreate method this line of code:
bindPreferenceSummaryToValue(findPreference(getString(R.string.key_upload_quality)));
and again, thanks for this amazing tutorial.
Good catch 🙂 All the best.
please help me.. sir, i need one things, how to create keep screen on/off using toggle switch? how to setting up this setting for my app.? I Hope U
What will happen when this option is enabled?
Sir,
Actualy i need source code
Find the code to lock screen that will turn off the screen.
Hi Ashok, here are the answers to your queries
1Q) I think keeping return; statement after super.onBackPressed() will resolve the issue as the code is keep executing after that statement.
2Q) To show a count in toolbar try the below code.
https://stackoverflow.com/questions/33729396/how-to-display-count-of-notifications-in-toolbar-icon-in-android
3Q) You can check whether is navigation drawer opened on backpress and close it. Keep the below code at the begging of onBackPress method.
Check the full code here in 16th step:
https://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
@Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
}
4Q) Just create a Preference activity separately. When the settings options from Navigation Drawer is selected, using index / id you can identify the item selected. If it matches with the index of settings option, start the preference activity. Something similar to below.
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
case R.id.nav_settings:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
Hi Ravi, how do I change the ellipsis that redirects to the Settings Screen to a gear icon?
Thanks
Vanessa
You need to modify the menu xml file by adding your icon.
Hi ravi my question is on different topic. the question is how can i show tap target view only for first time when the activity is opend ??
You can keep a boolean flag in shared preferences indicating first time app launch. If the value is true, do your action and store the firstTimeOpen value as false. Shared Preferences tutorial:
https://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
Hallo Ravi, Thanks for the above explanations this was what i was searching for only i need on more step to understand and i did not found it anywhere so far.
Could you explain how how to get and set the values programmaticaly. What i try to do is filling a database with the values set in the settings Activity. Is that possible and when so, can you give me some directions?
hey,
I did exactly according to your tutorial, but the back button on actionBar in somehow not working.
Any idea where I may be going wrong.
Thanks,
Shadman.
Did you overridden the onOptionsMenuSelected method?
Hey,
BIG THANKS @Ravi Tamada:disqus.
I missing it,
You are welcome 😀
sir, how i can add toolbar to preferences settings if i use noactionbar theme for app root? thx before
You can try this solution.
https://stackoverflow.com/questions/30139548/how-to-add-toolbar-in-preferenceactivity
hi ravi, i want to add font preference for this lesson, please give me tutorial or references. thank a lot
Hi Ravi, thanks for the tutorial. I am doing right now, do you have a example on how to add a seekbarpreference?
Have you tried writing any code?
I’ve tried making a separate layout and using it like this
Hence, the problem is that its attributes differ from SwitchPref or any other Pref objects.
Hi Ravi,
Why my checkbox color of checkbox preference is not changing ?
It’s always white when enabled.
Can you tell me what might be the reason ?
What is the accentColor in colors.xml?
How to set an icon on the right side of Edit Preference
Sir ! i want to create notification using seekbar on message notification firebase in android studio.How can i do it?
Thanks a lot for this tutorial. SeekBarPreference is missing. Can you pls add that too ?
i want to make these vibrate and sounds switches perform their respective tasks, but these are just dummy switches . can you please help how to on/off vibration or sound using these switches , i am making a location based reminder application. i am new in android so dont know much about it please help
android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cant find R.id.toolbar help please
want to set background theme what can i do for it
Hey Ravi, Je suis ravi de découvrir cette article 😉
Just to add something that took me a while before resolving it, is the “arrays.xml” must be in “res ⇒ values” folder. Adversely stated in the third step in Creating New Project :
“Create new xml named arrays.xml under res ⇒ arrays.xml”
Great, but for send email prefere use ShareCompat.IntentFilter…
Hi Ravi,
Is there a way we can add a read only property in device settings for own app (Device Settings -> APP -> OWN APP INFO/DETAILS PAGE)
Out of curiosity Im asking,why do we need to write so much of boiler plate code just to create a menu. Shouldn’t developers be more focusing on writing the business logic?
I think exactly the same. I’m just starting with android development and I find absurd that in 2019 we are required to write this quantity of boilerplate to achieve simple tasks that almost every app needs to do
Done by myself