How to show and hide preferences on Android dynamically? - android

Is there a way to dynamically show and hide preferences? In my case, I have a checkbox preference that would disable or enable one of 2 preference groups ("with-" and "without-handicap" groups). While this would be the ideal GUI in a desktop environment, the "with-handicap" takes up nearly the whole screen, while the other, "without-handicap" takes up only a small portion of the screen.
Rather than showing both groups at the same time, I'd like to show only one of them at a time, and dynamically show or hide the 2 groups when the checkbox changes. Is there a way to do this?

From a PreferenceActivity call
Preference somePreference = findPreference(SOME_PREFERENCE_KEY);
PreferenceScreen preferenceScreen = getPreferenceScreen();
preferenceScreen.removePreference(somePreference);
you can later call:
preferenceScreen.addPreference(somePreference);
The only a little bit tricky part is getting the order correct when adding back in. Look at PreferenceScreen documentation, particularly it's base class, PreferenceGroup for details.
Note: The above will only work for immediate children of a PreferenceScreen. If there is a PreferenceCategory in between, you need to remove the preference from its parent PreferenceCategory, not the PreferenceScreen. First to ensure the PreferenceCategory has an android:key attribute set in the XML file. Then:
Preference somePreference = findPreference(SOME_PREFERENCE_KEY);
PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference(SOME_PREFERENCE_CATEGORY_KEY);
preferenceCategory.removePreference(somePreference);
and:
preferenceCategory.addPreference(somePreference);

Not exactly hiding/showing but if you only want disabling/enabling preference depending on another preference you can specify android:dependency="preferenceKey" or Preference.setDependency(String)
Example from developer.android.com:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="pref_sync"
android:title="#string/pref_sync"
android:summary="#string/pref_sync_summ"
android:defaultValue="true" />
<ListPreference
android:dependency="pref_sync"
android:key="pref_syncConnectionType"
android:title="#string/pref_syncConnectionType"
android:dialogTitle="#string/pref_syncConnectionType"
android:entries="#array/pref_syncConnectionTypes_entries"
android:entryValues="#array/pref_syncConnectionTypes_values"
android:defaultValue="#string/pref_syncConnectionTypes_default" />
</PreferenceScreen>

I recommend using V7 preference, it has setVisible() method. But I have not tried it yet.

If you want to implement the hiding of the preference completely in the Preference, here is one example. Does not allow to make it visible again, though.
public class RemovablePreference extends Preference {
#Override
protected void onBindView(View view) {
super.onBindView(view);
updateVisibility(); // possibly a better place available?
}
private void updateVisibility() {
Context context = getContext(); // should be a PreferenceActivity
if (context instanceof PreferenceActivity) {
updateVisibility((PreferenceActivity)context);
}
}
private void updateVisibility(PreferenceActivity activity) {
updateVisibility(getPreferenceScreen(activity));
}
private PreferenceScreen getPreferenceScreen(PreferenceActivity activity) {
if (activity.getPreferenceScreen() != null) {
return activity.getPreferenceScreen(); // for old implementations
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Fragment fragment = activity.getFragmentManager().findFragmentById(android.R.id.content);
if (fragment instanceof PreferenceFragment) {
return ((PreferenceFragment) fragment).getPreferenceScreen();
}
}
return null;
}
private void updateVisibility(PreferenceScreen screen) {
if (!isVisible() && screen != null) {
hidePreference(screen, this);
}
}
private boolean hidePreference(PreferenceGroup prefGroup, Preference removedPreference) {
boolean removed = false;
if (prefGroup.removePreference(removedPreference)) {
removed = true;
}
for (int i = 0; i < prefGroup.getPreferenceCount(); i++) {
Preference preference = prefGroup.getPreference(i);
if (preference instanceof PreferenceGroup) {
PreferenceGroup prefGroup2 = (PreferenceGroup)preference;
if (hidePreference(prefGroup2, this)) {
// The whole group is now empty -> remove also the group
if (prefGroup2.getPreferenceCount() == 0) {
removed = true;
prefGroup.removePreference(prefGroup2);
}
}
}
}
return removed;
}
protected boolean isVisible() {
return true; // override
}

I needed something similar: toggling a switch to hide or show two extra preferences. Check out the sample app from Android-Support-Preference-V7-Fix which bring some new preference types and fixes some issues from the official library. There's an example there to toggle a checkbox to show or hide a preference category.
In the fragment that extends PreferenceFragmentCompatDividers, you could use something like:
findPreference("pref_show_extra_stuff").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
findPreference("pref_extra_stuff_01").setVisible((Boolean) newValue);
findPreference("pref_extra_stuff_02").setVisible((Boolean) newValue);
return true;
}
});
pref_extra_stuff_01 and pref_extra_stuff_02 are the two preferences that are hidden when pref_show_extra_stuff is toggled.

For hiding preferences dynamically, I created an if-condition upon whose value I decide whether I want the pref to show or not. To do the actual hiding, I have been using:
findPreference(getString(R.string.pref_key)).setLayoutResource(R.layout.hidden);
The tricky part is to make it visible again. There is no direct way to do it except to recreate the layout. If the value of the if-condition is false, which means the pref should be visible, then the code to hide the pref will never be executed, thus resulting in a visible pref. Here is how to recreate the layout (in my case, I am extending a PreferencesListFragment):
getActivity().recreate();
I hope that was helpful.

Instead of doing this in onCreate in the settings activity:
getSupportFragmentManager().beginTransaction()
.replace(R.id.settings_container, new SettingsFragment()).commit();
You can initialize a global variable for the settings fragment and set it up like this:
settingsFragment = new SettingsFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.settings_container, settingsFragment).commit();
Then further down you can set up an OnSharedPreferenceChangeListener with a global SharedPreferences.OnSharedPreferenceChangeListener to set up what should be shown or hidden when you change preferences:
// Global SharedPreferences.OnSharedPreferenceChangeListener
sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key)
{
if (key.equals("switch key"))
{
boolean newPref = preferences.getBoolean("switch key", true);
settingsFragment.findPreference("seekbar key").setVisible(newPref);
}
}
};
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
Then in onCreate in the settings fragment you can do something like this to set what should be hidden based on existing preferences:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
if (!sharedPreferences.getBoolean("switch key", true)
{
SeekBarPreference seekBarPreference = findPreference("seekbar key");
seekBarPreference.setVisible(false);
}

Related

Programatically make LinearLayout dismissible in android studio using shared preference

There is this thing I want to achieve, I have searched all questions on SO and no answer related to this, so I guess no one has asked which makes me curious.
On my XML, Android studio app, I added a Linear Layout, under the Linear layout, I added a 《TextView with text "Dismiss"》.
I want to set an onclick listener to this textview, once user clicks this TextView with text "Dismiss" I don't want that user to see that Linear Layout again on the page until they reinstall the app.
Logically, the Linear Layout will be like a notice to highlight something on my app when users arrive at that page, but instead of that notice to stay there forever I want user to be able to dismiss it which shows they have gotten the notice.
My workings:
Since I want each app user to decide not to see that text again after clicking dismiss, I need to use shared preference on that TextView with text "Dismiss", so whenever app gets the value of this shared preference then it will hide that layout.
I can set the LinearLayout to be invisible if that value from shared preference is found when stored on the app
The question now, how will I set this shared preference and which code will I use to make the Layout "GONE" or "INVISIBLE" if the TextView with text "Dismiss" is clicked?
Your intelligent solution to this will be much appreciated.
check this out , its in Java, and this will hide the layout after clicking the dismisstextview and when u re open it alert will still be hidden.
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = getSharedPreferences(getApplicationContext().getPackageName(),0);
editor = sharedPref.edit();
LinearLayout alertLayout = (LinearLayout)findViewById(R.id.alertLayout);
TextView textViewDismiss = (TextView)findViewById(R.id.textViewDismiss);
if(sharedPref.getBoolean("isLayoutAlertShown",false)){
alertLayout.setVisibility(View.GONE);
}else{
alertLayout.setVisibility(View.VISIBLE);
}
textViewDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertLayout.setVisibility(View.GONE);
editor.putBoolean("isLayoutAlertShown",true);
editor.apply();
}
});
}
}
I would recommend you to use SharedPreferences since this is related to setting matter. You can refer to this link: https://developer.android.com/training/data-storage/shared-preferences#java
You have to call this method at the onCreate. So it will check if the there is showLayout stated true or false, then it will update the design.
//Inside onCreate
private void initSharedPreference(final Activity activity, final LinearLayout linearLayout) {
final SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
if (sharedPref.getBoolean("showLayout", false)) {
linearLayout.setVisibility(View.GONE);
} else {
linearLayout.setVisibility(View.VISIBLE);
}
}
At the setOnClickListener you need to implement this method.
//At the button
private void setSharedPrefShowLayout(final Activity activity, final Boolean isVisible) {
final SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("showLayout", isVisible);
editor.apply();
}

Add preferences to specific places in PreferenceScreen programmatically

I am populating parts of my preferences programmatically. This works fine. Unfortunately new preferences there has to be added, when the user changes some preferences (think of an 'add a new alarm'-preference). This works fine as well, when I use PreferenceCategories (because the new ones are added at the end of one such, so myPreferenceCategory.addPreference(newPreference) does the trick). But what can I do to programmatically add a Preference to any specific place (not just the end of usual categories/the prefScreen??
I tried to use some kind of "invisible" PreferenceCategory, by setting android:layout="my_custom_invis_layout" with
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_custom_invis_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="0dp"
android:paddingTop="0dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"/>
Unfortunately those padding and margin does not seem to have an impact on the minimum space the empty category take (but do so with positive values, which is - of cause - of no help).
I tried as well to nullify the layout by
<PreferenceCategory
android:layout="#null">
but this just enlarges the space the category takes to those the other preferences have.
Unfortunately SO did not help me on this so far. I would be very happy if anyone can point me to something like "add a preference A below preference B" or on how to make a category taking no space at all (as this would resolve my problem as well).
I see this question is quite old, but since I was facing a similar problem and managed to solved it, I figured there would be no harm done by posting anyway.
The way I solved this is by adding the Preference (in my case a category that needed to be added in a particular spot amongst the other categories) in xml from the start, removing it programmatically if not yet needed. When putting it back (programmatically) afterwards, it appears at the same position it was before removing it. Haven't tried your particular case (with single Preferences needing to go in a particular spot within a category), but I bet it works the same way.
public class PreferencesFragment extends PreferenceFragmentCompat {
private SharedPreferences mSharedPreferences;
private PreferenceCategory mPreferenceCategory;
#Override
public void onCreatePreferences(#Nullable Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.preferences);
mPreferenceCategory = (PreferenceCategory) findPreference("preferenceCategoryKey");
if (preferenceNotRequiredYet) {
removePreferenceCategory();
}
// an I have a SharedPreferenceListener attached that calls
// addPreferenceCategory when I need to add it back
}
private void removePreferenceCategory() {
PreferenceScreen parentScreen = (PreferenceScreen) findPreference("parent_screen_key");
parentScreen.removePreference(mPreferenceCategory);
}
private void addPreferenceCategory() {
PreferenceScreen parentScreen = (PreferenceScreen) findPreference("parent_screen_key");
parentScreen.addPreference(mPreferenceCategory);
}
}
Ok, I've tried that other approach with Preferences#setOrder(int). (I left the previous answer there, cause for some use cases it might be the easier solution.) Does this one better suit your needs?
public class PreferencesFragment extends PreferenceFragmentCompat {
private SharedPreferences mSharedPreferences;
PreferenceCategory mMyPreferenceCategory;
// ArrayList to keep track of the currently added Preferences
ArrayList<Preference> mPreferenceList = new ArrayList<>();
// this counter only serves for name-giving of the added
// Preferences in this example
int mCounter = 0;
#Override
public void onCreatePreferences(#Nullable Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.preferences);
mMyPreferenceCategory = (PreferenceCategory) findPreference("preferenceCategoryKey");
addPreference(null);
}
// adds a Preference that is inserted on the position of the
// clicked Preference, moving the clicked Preference - and all
// Preferences after - one position down
private void addPreference(Preference pref) {
int order = 0;
if (pref != null) {
order = pref.getOrder();
}
for (Preference preference : mPreferenceList) {
int oldOrder = preference.getOrder();
if (oldOrder >= order) {
preference.setOrder(oldOrder+1);
}
}
Preference newPreference = new Preference(getContext());
newPreference.setTitle("Preference " + mCounter);
newPreference.setOrder(order);
newPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
addPreference(preference);
return false;
}
});
mMyPreferenceCategory.addPreference(newPreference);
mPreferenceList.add(newPreference);
mCounter++;
}
}

How to hide dependent Edittextpreferences when a Checkboxpreference is checked?

I have a CheckBoxPreference and two EditTextPreferences which are dependent on the CheckBoxPreference (all defined in an xml file and all three together inside a single PreferenceScreen).
My question is this: How to hide and redisplay those two EditTextPreferences when the user unchecks and checks the Checkboxpreference respectively?
Currently I am just able to enable/disable them by adding the android:dependency attribute to them.
Solutions to do so in java or in xml will be appreciated. :)
I'm not aware of anyway to do this through xml, which always my preferred choice. But this java solution should work.
CheckBoxPreference chkPref = (CheckBoxPreference)findPreference("myCheckPref");
EditTextPreference editPref1 = (EditTextPreference)findPreference("myEditCheckPref");
PreferenceGroup editTextParent = getParent(editPref1);
chkPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
public boolean onPreferenceChange(Preference pref, Object value)
{
if(value)
editTextParent.addPreference(editPref1);
else
editTextParent.removePreference(editPref1);
return true;
}
});
As there is no in built way to find the parent group of a parent, you will also have to define these functions:
private PreferenceGroup getParent(Preference preference)
{
return getParent(getPreferenceScreen(), preference);
}
private PreferenceGroup getParent(PreferenceGroup root, Preference preference)
{
for (int i = 0; i < root.getPreferenceCount(); i++)
{
Preference p = root.getPreference(i);
if (p == preference)
return root;
if (PreferenceGroup.class.isInstance(p))
{
PreferenceGroup parent = getParent((PreferenceGroup)p, preference);
if (parent != null)
return parent;
}
}
return null;
}

How to navigate to nested PreferencesScreen

in my app I have nested PreferencesScreen's
<PreferencesScreen>
<PreferencesScreen android:key="application">
</PreferencesScreen>
</PreferencesScreen>
Now I want to fire Intent to take me from currrent Activity directly to application preferences subscreen. How can I do this?
In my application I have the similar task to show second-level PreferencesScreen programmatically. What I did:
In preferences.xml I assigned a key to PreferencesScreen I want to show (as shown in the question).
To show PreferencesScreen I wrote:
final Intent preferencesActivity = new Intent(getBaseContext(), MyPreferencesActivity.class);
preferencesActivity.putExtra("PREFERENCE_SCREEN_KEY", "key_of_preference_screen_to_show");
startActivity(preferencesActivity);
Then in my PreferenceActivity class in method onCreate the following code was added:
final Intent intent = getIntent();
final String startScreen = intent.getStringExtra("PREFERENCE_SCREEN_KEY");
if (startScreen != null) {
getIntent().removeExtra("PREFERENCE_SCREEN_KEY");
final Preference preference = findPreference(startScreen);
final PreferenceScreen preferenceScreen = getPreferenceScreen();
final ListAdapter listAdapter = preferenceScreen.getRootAdapter();
final int itemsCount = listAdapter.getCount();
int itemNumber;
for (itemNumber = 0; itemNumber < itemsCount; ++itemNumber) {
if (listAdapter.getItem(itemNumber).equals(preference)) {
preferenceScreen.onItemClick(null, null, itemNumber, 0);
break;
}
}
}
One remark... Not only second-level PreferencesScreen, but the whole preferences hierarchy was loaded here. So, if you press Back button, the first (parent) PreferencesScreen will appear. In my case that was exactly what I needed. Not sure about yours.
Here is a way of handling the problem by grabbing the child-screen up front:
public class MyChildPreferenceActivity extends PreferenceActivity {
private String screenKey = "myChildScreenKey";
#Override
public PreferenceScreen getPreferenceScreen() {
PreferenceScreen root = super.getPreferenceScreen();
if (root != null) {
PreferenceScreen match = findByKey(root, screenKey);
if (match != null) {
return match;
} else {
throw new RuntimeException("key " + screenKey + " not found");
}
} else {
return null;
}
}
private PreferenceScreen findByKey(PreferenceScreen parent, String key) {
if (key.equals(parent.getKey())) {
return parent;
} else {
for (int i = 0; i < parent.getPreferenceCount(); i++) {
Preference child = parent.getPreference(i);
if (child instanceof PreferenceScreen) {
PreferenceScreen match = findByKey((PreferenceScreen) child, key);
if (match != null) {
return match;
}
}
}
return null;
}
}
// ...
I resolved your exact same issue this way.
In your preference activity:
#Override
protected void onResume() {
super.onResume();
int startingPage = getIntent().getIntExtra(Constants.PREFS_STARTING_PAGE, 0);
switch (startingPage) {
case Constants.MY_PREF_SCREEN_1:
setPreferenceScreen((PreferenceScreen)findPreference(getString(R.string.PREF_SCREEN_1)));
break;
case Constants.MY_PREF_SCREEN_2:
setPreferenceScreen((PreferenceScreen)findPreference(getString(R.string.PREF_SCREEN_2)));
break;
default:
// Nothing to do, but read the warning below.
}
}
Then you can open the inner preference screen with something like this:
Intent prefIntent = new Intent(ctx, MyPreferenceActivity.class);
prefIntent.putExtra(Constants.PREFS_STARTING_PAGE, Constants.MY_PREF_SCREEN_1);
startActivity(prefIntent);
Beware that this works as long as the activity instances are different: one instance for the main preference screen and another for the inner screen. In this way, when you start the activity without "launch" parameter, you always fall into the default switch case and never need to set the main preference screen. The problem here is that if you first run the activity starting with an inner pref screen and then lauch the SAME activity (with the flag singleInstance, for example) asking for the general (root) pref screen, you're not able to call findPreference() to find the root preference screen from inside a child preference screen.
Well, hope to have not made too much confusion ;-)
The way I use is to put nested PreferenceScreen into a separate XML file and use it in other PreferenceActivity. In this case you'll be able to navigate to this screen from preferences using Preference.setIntent() and start this Activity in a usual way from another Activity.

How to open or simulate a click on an android Preference, created with XML, programmatically?

I've an android application with preferences declared in XML, loaded with addPreferencesFromResource. The user can open preferences, click on each item and edit them, all works.
One preference I have is:
<ListPreference android:key="abc"
android:title="#string/abc"
android:summary="#string/cde"
android:persistent="true"/>
How can I show the preference dialog to a user automatically (without the need for the user to go to the preference screen and click on it?).
I tried ( (android.preference.DialogPreference) prefMgr.findPreference( "abc" )).showDialog(null), but is says it is a protected method...? Called it from my main activity (which is a PreferenceActivity), that's why it obviously cannot work. But how else?
EDIT
I just found two threads (1, and 2) with the idea to use findViewById to access the preference, but with no success. It always returns null (does for me, too).
It looks like there is really no possibility to do this from code.
See the new accepted answer for a much cleaner approach! This was working, but not really the clean way of doing it.
Damn it, it got me several hours, but it finally works.
The solution is the undocumented call public void onItemClick (...). It takes several arguments, and as pointed out by this question it can be used to simulate a click according to the index of the element you want to call.
My problem was the item I want to call is deeply nested in an XML-structure. But the solution is very easy: add a key to the PreferenceScreen the item you want to open is in:
<PreferenceScreen
android:key="pref_key"
....
/>
<ListPreference android:key="abc"
android:title="#string/abc"
android:summary="#string/cde"
android:persistent="true"/>
</PreferenceScreen>
And the you can just to the following:
// the preference screen your item is in must be known
PreferenceScreen screen = (PreferenceScreen) findPreference("pref_key");
// the position of your item inside the preference screen above
int pos = findPreference("abc").getOrder();
// simulate a click / call it!!
screen.onItemClick( null, null, pos, 0 );
And the Dialog pops up!
It would be nice to get the PreferenceScreen a Preference is in (so you would not have to know where your Preference is in), because moving the preference/changing the XML could break the automatic dialog silently and might not get noticed (if not tested).
For this I wrote a function which will search through all preferences and return the PreferenceScreen your preference is on, so you don't need to have your PreferenceScreen a key!
private PreferenceScreen findPreferenceScreenForPreference( String key, PreferenceScreen screen ) {
if( screen == null ) {
screen = getPreferenceScreen();
}
PreferenceScreen result = null;
android.widget.Adapter ada = screen.getRootAdapter();
for( int i = 0; i < ada.getCount(); i++ ) {
String prefKey = ((Preference)ada.getItem(i)).getKey();
if( prefKey != null && prefKey.equals( key ) ) {
return screen;
}
if( ada.getItem(i).getClass().equals(android.preference.PreferenceScreen.class) ) {
result = findPreferenceScreenForPreference( key, (PreferenceScreen) ada.getItem(i) );
if( result != null ) {
return result;
}
}
}
return null;
}
private void openPreference( String key ) {
PreferenceScreen screen = findPreferenceScreenForPreference( key, null );
if( screen != null ) {
screen.onItemClick(null, null, findPreference(key).getOrder(), 0);
}
}
// With this, you can call your `Preference` like this from code, you do
// not even have to give your PreferenceScreen a key!
openPreference( "abc" );
You could have extended ListPreference to create your dialog, then included your own public method that calls the protected showDialog method of ListPreference. Something like:
public void show()
{
showDialog(null);
}
This way you won't run into the issue of getOrder() not working when there are PreferenceGroups as several people have pointed out in the comments your answer.
This can be done with any preference types that has a protected showDialog method.
If you use the support library you can open a dialog easily with PreferenceManager.showDialog(Preference).
In your PreferenceFragmentCompat:
getPreferenceManager().showDialog(findPreference("pref_name"));
Note that support preference package has many issues:
non-material styling and
it crashes when rotated with an open dialog.
PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("pref_key");
final ListAdapter listAdapter = preferenceScreen.getRootAdapter();
EditTextPreference editPreference = (EditTextPreference) findPreference("set_password_preference");
final int itemsCount = listAdapter.getCount();
int itemNumber;
for (itemNumber = 0; itemNumber < itemsCount; ++itemNumber) {
if (listAdapter.getItem(itemNumber).equals(editPreference)) {
preferenceScreen.onItemClick(null, null, itemNumber, 0);
break;
}
}
}
}
Improving deepak goel's answer:
private void openPreference(String key) {
PreferenceScreen preferenceScreen = getPreferenceScreen();
final ListAdapter listAdapter = preferenceScreen.getRootAdapter();
final int itemsCount = listAdapter.getCount();
int itemNumber;
for (itemNumber = 0; itemNumber < itemsCount; ++itemNumber) {
if (listAdapter.getItem(itemNumber).equals(findPreference(key))) {
preferenceScreen.onItemClick(null, null, itemNumber, 0);
break;
}
}
}
If you're using AndroidX Preference library, it is quite simple.
public class CustomPreferenceFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.your_preference);
DialogPreference dialogPreference = (DialogPreference) findPreference("your_preference_key");
onDisplayPreferenceDialog(dialogPreference);
}
}
wait, u can do something like this as well
Preference p=findPreference("settings_background_color");
p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
int color=PreferenceManager.getDefaultSharedPreferences(ALifePatternsWallpaperSettings.this).getInt("settings_background_color", Color.BLACK);
new ColorPickerDialog(ALifePatternsWallpaperSettings.this, ALifePatternsWallpaperSettings.this, "settings_background_color", color, Color.BLACK).show();
return true;
}
});
hi friends try this code in works fine
getPreferenceManager().findPreference("YOUR PREF_KEY").setOnPreferenceClickListener(new OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
//your code here
return true;
}
});

Categories

Resources