Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open or simulate click on android ListPreference, which is inside preference category?

I'm trying to open programatically a ListPreference, which exist inside PreferenceCategory. The XML structure is something like:

<PreferenceScreen 
    android:key="pref_screen" >

    <PreferenceCategory 
        android:title="Category"
        andorid:key="pref_category">
        <ListPreference
            android:key="pref_list"
            android:title="List" />
    </PreferenceCategory>
</PreferenceScreen> 

My goal is to open "pref_list" programatically, and display it to the user. I looked into this topic, offering this solution:

// the preference screen your item is in must be known
PreferenceScreen screen = (PreferenceScreen) findPreference("pref_screen");

// the position of your item inside the preference screen above
int pos = findPreference("pref_list").getOrder();

// simulate a click / call it!!
screen.onItemClick( null, null, pos, 0 ); 

This works perfectly for a PreferenceScreen without PreferenceCategory, but I can't get it working for my case (When the ListPreference is located inside PreferenceCategory).

How can I modify this for my case? Or is there any other solution?

I couldn't find in PreferenceCategory a method, similar to onItemClick() of PreferenceScreen. Changing 'pos' for the getOrder() value of my PreferenceCategory did not work as well.

like image 692
alexgo91 Avatar asked Oct 01 '12 10:10

alexgo91


1 Answers

I know it's a very old thread but I've just had similar problem so here my short solution based on this one

    ListAdapter listAdapter = getPreferenceScreen().getRootAdapter();

    for (int itemNumber = 0; itemNumber < listAdapter.getCount(); itemNumber++)
        if (listAdapter.getItem(itemNumber).equals(findPreference("pref_list")))
            getPreferenceScreen().onItemClick(null, null, itemNumber, 0);
like image 167
sZpak Avatar answered Nov 12 '22 20:11

sZpak