I want to update my activity immediately after a user changes a setting like language or time format.
Here is my code:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
public static final String HOUR_FORMAT = "hourFormat";
public static final String LANGUAGE_CHOICE = "languageSelection";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("hourFormat")) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(Boolean.toString(sharedPreferences.getBoolean(key, true)));
}
else if(key.equals("languageSelection")) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, "English"));
}
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}
This is preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="hourFormat"
android:title="#string/hour24"
android:summary="#string/hour24Explanation"
android:defaultValue="true" />
<ListPreference
android:key="languageSelection"
android:entries="#array/languageValues"
android:summary="#string/languageSelection"
android:entryValues="#array/languageValues"
android:title="#string/language" />
</PreferenceScreen>
This only works, if i restart the app. However I want to update it immediately just after the change? (If you want, I can provide other source codes in my app, I know there are lots of resources but I couldn't get this thing working.)
I also think I don't really understand the xListener concept in Java. I read about it a lot but can you clarify or provide additional links to me.
Thanks, in advance.
You need to receive the system triggers when the user changes them. To do this, you need to have a class to receive the information, for example for the Time change, put this class in the main Activity class:
private final BroadcastReceiver timeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED) ||
action.equals(Intent.ACTION_TIMEZONE_CHANGED))
{
doStuffYouNeedToDo();
}
}
};
Write a method doStuffYouNeedToDo in the Activity which does whatever you need to when the time or timezone is changed. To make sure it is called, put this in your class:
// For intent filter for catching timezone etc changes
private static IntentFilter timeChangeIntentFilter;
static {
timeChangeIntentFilter = new IntentFilter();
timeChangeIntentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
timeChangeIntentFilter.addAction(Intent.ACTION_TIME_CHANGED);
}
and this in onCreate:
registerReceiver(timeChangedReceiver, timeChangeIntentFilter);
And to stop it when the Activity stops, put this in onDestroy:
unregisterReceiver(timeChangedReceiver);
Related
My application users can change the language from the app's settings. Is it possible to change the language inside the application without having effect to general language settings ?
This question of stackoverflow is very useful to me and i have tried it. After changing language newly created activities display with changed new language, but current activity and previously created activities which are in pause state are not updated.How to update activities ?
I have also spent a lot of time trying to make the preference change to be applied immediately but didn't succeed. When application is restarted, all activities created again, so now language changed correctly.
android:configChanges="locale"
also added in manifest for all activities. and also support all screen.
Currently I have not done any thing in activity's onResume() method.
Is there any way to refresh or update activity (without finish and starting again) ? Am I missing something to do in onResume() method?
After changing language newly created activities display with changed new language, but current activity and previously created activities which are in pause state are not updated.How to update activities ?
Pre API 11 (Honeycomb), the simplest way to make the existing activities to be displayed in new language is to restart it. In this way you don't bother to reload each resources by yourself.
private void restartActivity() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
Register an OnSharedPreferenceChangeListener, in its onShredPreferenceChanged(), invoke restartActivity() if language preference was changed. In my example, only the PreferenceActivity is restarted, but you should be able to restart other activities on activity resume by setting a flag.
Update (thanks #stackunderflow): As of API 11 (Honeycomb) you should use recreate() instead of restartActivity().
public class PreferenceActivity extends android.preference.PreferenceActivity implements
OnSharedPreferenceChangeListener {
// ...
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("pref_language")) {
((Application) getApplication()).setLocale();
restartActivity();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStop() {
super.onStop();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
I have a blog post on this topic with more detail, but it's in Chinese. The full source code is on github: PreferenceActivity.java
If I imagined that you set android:configChanges in manifest.xml and create several directory for several language such as: values-fr OR values-nl, I could suggest this code(In Activity class):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// change language by onclick a button
Configuration newConfig = new Configuration();
newConfig.locale = Locale.FRENCH;
onConfigurationChanged(newConfig);
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
setContentView(R.layout.main);
setTitle(R.string.app_name);
// Checks the active language
if (newConfig.locale == Locale.ENGLISH) {
Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
} else if (newConfig.locale == Locale.FRENCH){
Toast.makeText(this, "French", Toast.LENGTH_SHORT).show();
}
}
I tested this code, It is correct.
Since the string resources will have already been loaded for the existing locale, the activities already opened will not automatically display using strings from the new locale. The only way to solve this is to reload all of the strings and set them again on the views. Typically, a call to setContentView(...) will be able to cover this (depending on your Activity structure), but of course it has the side-effect of losing any view state you had.
public void onResume() {
super.onResume();
...
if (localeHasChanged) {
setContentView(R.layout.xxx);
}
...
}
You will probably not want to reload the views every single time in onResume(), but only when the locale has changed. Checking when to update the views (i.e. localeHasChanged) is a matter of propagating the locale change event to the previous activities. This could be done in many ways, such as using static singleton-esque state or persisting this event to storage.
You could also try to minimise the number of Activities that can be opened when you can change the locale, e.g. by having the selection be at one of the initial screens.
For Android 4.2 (API 17), you need to use android:configChanges="locale|layoutDirection" in your AndroidManifest.xml. See onConfigurationchanged is not called over jellybean(4.2.1)
You can use recreate(); to restart your activity when Language change.
I am using following code to restart activity when language change:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Configuration config = getBaseContext().getResources().getConfiguration();
String lang = settings.getString("lang_list", "");
if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang)) {
recreate(); //this is used for recreate activity
Locale locale = new Locale(lang);
Locale.setDefault(locale);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
The way we have done it was using Broadcasts:
Send the broadcast every time the user changes language
Register the broadcast receiver in the AppActivity.onCreate() and unregister in AppActivity.onDestroy()
In BroadcastReceiver.onReceive() just restart the activity.
AppActivity is the parent activity which all other activities subclass.
Below is the snippet from my code, not tested outside the project, but should give you a nice idea.
When the user changes the language
sendBroadcast(new Intent("Language.changed"));
And in the parent activity
public class AppActivity extends Activity {
/**
* The receiver that will handle the change of the language.
*/
private BroadcastReceiver mLangaugeChangedReceiver;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
// Other code here
// ...
// Define receiver
mLangaugeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
startActivity(getIntent());
finish();
}
};
// Register receiver
registerReceiver(mLangaugeChangedReceiver, new IntentFilter("Language.changed"));
}
#Override
protected void onDestroy() {
super.onDestroy();
// ...
// Other cleanup code here
// ...
// Unregister receiver
if (mLangaugeChangedReceiver != null) {
try {
unregisterReceiver(mLangaugeChangedReceiver);
mLangaugeChangedReceiver = null;
} catch (final Exception e) {}
}
}
}
This will also refresh the activity which changed the language (if it subclasses the above activity).
This will make you lose any data, but if it is important you should already have taken care of this using Actvity.onSaveInstanceState() and Actvity.onRestoreInstanceState() (or similar).
Let me know your thoughts about this.
Cheers!
Step by Step Approach Complete Approach which will work on all API level device.
Using this apporach, It will work without Recreating the existing Activity on screen
Use Base Activity for attachBaseContext to set the locale language and extend this activity for all activities
open class BaseAppCompactActivity() : AppCompatActivity() {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(LocaleHelper.onAttach(newBase))
}
}
Use Application attachBaseContext and onConfigurationChanged to set the locale language
public class MyApplication extends Application {
/**
* overide to change local sothat language can be chnaged from android device nogaut and above
*/
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.INSTANCE.onAttach(base));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
setLanguageFromNewConfig(newConfig);
super.onConfigurationChanged(newConfig);
}
/*** also handle chnage language if device language chnaged **/
private void setLanguageFromNewConfig(Configuration newConfig){
Prefs.putSaveLocaleLanguage(this, selectedLocaleLanguage );
LocaleHelper.INSTANCE.onAttach(this);
}
}
Use Locale Helper for handling language changes, this approach work on all device
object LocaleHelper {
private var defaultLanguage :String = KycUtility.KYC_LANGUAGE.ENGLISH.languageCode
fun onAttach(context: Context, defaultLanguage: String): Context {
return setLocale(context, defaultLanguage)
}
fun setLocale(context: Context, language: String): Context {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResources(context, language)
} else updateResourcesLegacy(context, language)
}
#TargetApi(Build.VERSION_CODES.N)
private fun updateResources(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val configuration = context.getResources().getConfiguration()
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
return context.createConfigurationContext(configuration)
}
private fun updateResourcesLegacy(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.getResources()
val configuration = resources.getConfiguration()
configuration.locale = locale
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale)
}
resources.updateConfiguration(configuration, resources.getDisplayMetrics())
return context
}
}
Call this method to change app locale:
public void settingLocale(Context context, String language) {
Locale locale;
Configuration config = new Configuration();
if(language.equals(LANGUAGE_ENGLISH)) {
locale = new Locale("en");
Locale.setDefault(locale);
config.locale = locale;
}else if(language.equals(LANGUAGE_ARABIC)){
locale = new Locale("hi");
Locale.setDefault(locale);
config.locale = locale;
}
context.getResources().updateConfiguration(config, null);
// Here again set the text on view to reflect locale change
// and it will pick resource from new locale
tv1.setText(R.string.one); //tv1 is textview in my activity
}
Note: Put your strings in value and values- folder.
I solved my problem with this code
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
onConfigurationChanged(conf);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
iv.setImageDrawable(getResources().getDrawable(R.drawable.keyboard));
greet.setText(R.string.greet);
textView1.setText(R.string.langselection);
super.onConfigurationChanged(newConfig);
}
Good day.
I know how to check if there is an internet connection available, my problem is that I want to present the user an AlertDialog that prevents action except trying again whenever the connection is lost or deactivated. What I don't know is how to code it only one time, so I don't need to replicate it manually in all activities.
I tried using Observer Pattern, and initialize it in SplashActivity(Launcher Activity).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ObservedObject observedObject = new ObservedObject();
observedObject.addObserver(new ObserverInternetConnection());
}
public class ObservedObject extends Observable {
private boolean isConnected;
public boolean isConnected() {
return isConnected;
}
public void setConnected(boolean connected) {
isConnected = connected;
setChanged();
notifyObservers();
}
public class ObserverInternetConnection implements Observer {
#Override
public void update(Observable observable, Object o) {
if (observable instanceof ObservedObject) {
if (observable.hasChanged())
//alert is a method to show toast message
alert("connection changed");
if (((ObservedObject) observable).isConnected)
alert("connected");
else
alert("disconnected");
}
}
}
It worked when I manually set the observedObject connection. But I want to avoid doing so. Is there a way to do this automatically? I was thinking of using another thread, but how could I do so?
another problem is that the way i check the internet connection is using ConnectivityManager but it need me to pass the context and the context can (and will) change throughout the application, how can I overcome so? Is there any other approach for the problem?
I would suggest to create BaseActivity where you are initializing connectivity change listener (Observer in your case) and extend this activity with Splash, Main and other activities that you are using.
This way you are going to avoid code duplication.
Also don't forget to unregister listeners when activity is destroyed.
Also you dont need to use different threads. Here is example how to listen connectivity changes in Activity:
Register receiver first:
#Override
public void register(Context context) {
initReceiver();
final IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(receiver, intentFilter);
}
receiver
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (isOnline()) {
hideNoConnectionError();
} else {
showNoConnectionError();
}
}
};
and isOnline()
val isOnline: Boolean
get() {
return try {
val connectivityManager = context.getSystemService(
Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.activeNetworkInfo != null &&
connectivityManager.activeNetworkInfo.isConnected
} catch (exception: Exception) {
false
}
}
sorry, last method is written in Kotlin, but I think it is completely understandable
One additional approach if your minimal SDK version >= N(24) would be to subscribe to ConectivityManager in Application class. In order to prevent user from interaction start transparrent activity on top with some shadowed background stating that connection lost. This is not ideal approach but you will not need to stick to inheritance.
TestApplication.java
public class TestApplication extends android.app.Application {
private static final String TAG = "TestApplication";
#Override
public void onCreate() {
super.onCreate();
ConnectivityManager m = (ConnectivityManager) getSystemService(Service.CONNECTIVITY_SERVICE);
m.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
Log.e(TAG, "onAvailable: ");
startActivity(ConnectionLostScreen.createIntentHideSplashOnNetworkRecovery(TestApplication.this));
}
#Override
public void onLost(Network network) {
Log.e(TAG, "onLost: ");
startActivity(ConnectionLostScreen.createShowSplashOnNetworkFailure(TestApplication.this));
}
});
}
}
ConnectionLostScreen.java
public class ConnectionLostScreen extends AppCompatActivity {
private final static int SHOW = 1;
private final static int HIDE = 2;
private final static String EXTRA_NAME = "ACTION";
public static Intent createShowSplashOnNetworkFailure(Context app) {
Intent intent = new Intent(app, ConnectionLostScreen.class);
intent.putExtra(EXTRA_NAME, SHOW);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);
return intent;
}
public static Intent createIntentHideSplashOnNetworkRecovery(Context app) {
Intent intent = new Intent(app, ConnectionLostScreen.class);
intent.putExtra(EXTRA_NAME, HIDE);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
if (getIntent() != null) handleIntent(getIntent());
}
#Override
public void onBackPressed() {
//disabled so user would not be able to close this activity.
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null) handleIntent(intent);
}
void handleIntent(Intent intent) {
int value = intent.getIntExtra(EXTRA_NAME, 0);
if (value == 0 || value == HIDE) {
finish();
return;
}
}
}
Theme for ConnectionLostScreen would be.
<style name="Theme.Transparent" parent="AppTheme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
Pros:
No inheritance.
Independent and works across application
No activity lifetime tracking
No need for Activity context as entire Activity acts like dialog.
Custom layout, graphic, animation could be integrated
No user action needed because when connection restored ConnectionLostScreen will be closed.
Cons:
Activity flow management for ConnectionLostScreen (making it
singleTop etc.)
Hard to make granular control if only certain
screens should be covered
Animations for Activity transitions
I have in my app preference activity with EditTextPreference and I added this, to detect, when the text in edittext is changed. All works, except for that, the code runs always twice... I tryed to add System.out.println("now"); to proove if the code runs twice, and it writes "now" two times...
Here is the code:
SharedPreferences.OnSharedPreferenceChangeListener myPrefListner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.admin_activity);
myPrefListner = new SharedPreferences.OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
switch(key) {
case "prefAddUser":
EditTextPreference connectionPref = (EditTextPreference) findPreference(key);
String jmeno = connectionPref.getText();
System.out.println("now");
add_user(jmeno); //custom method to add user to MySQL database
Toast.makeText(getApplicationContext(), "add user", Toast.LENGTH_SHORT).show();
connectionPref.setText("");
break;
}
}
};
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(myPrefListner);
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(myPrefListner);
}
I don't know what to do with this weird problem...
What should I do?
Calling OnSharedPreferenceChangeListener in anonymous class makes it become the target of garbage collection.
As soon as you leave the current scope and can cause unregisterOnSharedPreferenceChangeListener() to be call on a null context.
Implement it in the class scope like this:
public class SettingsActivity extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "pref_syncConnectionType";
...
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(KEY_PREF_SYNC_CONN)) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
Read the next tutorials for further explanation:
1. Good So answer on the subject
2. Official documentation here
I have the first class named iHave
public class iHave extends ActionBarActivity
{
//below is the instance for calling the method from the other activity.
(The name of the other activity is **iThank**)
**iThank thankYou = new iThank();**
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_have);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
**//this is the method I want to access from iThank class** **strong text**
thankYou.display();
}
});
}
//The Next class is "iThank"
public class iThank extends ActionBarActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_thank);
txtThank = (TextView) findViewById(R.id.textView3);
//this is the method I want to access/use from iHave Activity
public void display()
{
txtThank.setText ("Shine");
}
}
How can I use the method "public void display()" of iThank activity to the "iHave" activity? It always gives me an error of NullPointerException. Please help. Thank you very much!
How can I access a method from an activity and use it into another
activity in Android?
By creating object for other to access method from Activity is right way.
Use LocalBroadcastManager for communicating between application components.
1. Send broadcast from iHave on Button click:
#Override
public void onClick(View v)
{
Intent intent = new Intent("DISPLAY_EVENT");
LocalBroadcastManager.getInstance(v.getContext()).sendBroadcast(intent);
}
2. Register LocalBroadcastManager in iThank Activity:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(ReceiveMessage,
new IntentFilter("DISPLAY_EVENT"));
}
3. Create BroadcastReceiver object and call display() method in iThank Activity:
private BroadcastReceiver ReceiveMessage = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
display();
}
};
Also add null check in display method for TextView:
public void display()
{
if(txtThank !=null)
txtThank.setText ("Shine");
}
Please don't to this, it is not how activities are intended to work. You might want to have a look over the Activities Developer Guide to get started. If you want to launch a new activity (e.g. iThank) from the current foreground activity (e.g. iHave), you never instantiate the class yourself directly and always launch it using an intent. If you have data to pass along (such as a message to display), it needs to be bundled along with the intent as an extra (see same link).
Activities should never call methods on each other directly, because this requires them to have references to each other. The framework manages the life cycle of each activity independently, and those references can lead to leaks.
I wanna display a dialog when the user selects a specific item from a ListPreference in my preferenceActivity. But, I cannot get the onSharedPreferenceChanged() to work. I've put a Toast in the beginning of the method, and it does not show, so the method doesn't even run through, why is this?
Here's my code: (Thanks)
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Toast.makeText(Preferences.this, "prefs Changed", Toast.LENGTH_SHORT)
.show();
if (key.equals("boolean_ad_type")) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String value = sharedPreferences.getString("boolean_ad_type", "");
if (value != null && value.equals("Pop-up Ads")) {
Toast.makeText(Preferences.this, "Pop-up Ads Selected",
Toast.LENGTH_SHORT).show();
}
}
}
And do I need to implement it in the activity like this? (I've tried with and without, no difference)
public class Preferences extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
onSharedPreferenceChanged not fired if change occurs in separate activity?
public class MyActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
you have to set a click listener for that specific preference you want to show the dialog in your onCreate
PreferenceScreen ps2 = (PreferenceScreen) findPreference("ic_vol");
ps2.setOnPreferenceClickListener(this);