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

2

6

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.

Labiovelar answered 1/10, 2012 at 10:29 Comment(0)
D
1

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);
Dramaturge answered 10/10, 2015 at 17:15 Comment(0)
M
-1

Offering a different solution, simulating a finger touch:

Use View.getLocationOnScreen() and/or getLocationInWindow() to get the position of the list item. So you can find a width and a height to simulate a click.

    MotionEvent me=MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, width, height, 0);
    rootView.dispatchTouchEvent(me);
    me=MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, width, height, 0);
    rootView.dispatchTouchEvent(me);
    me.recycle();
Magness answered 28/3, 2013 at 8:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.