Search code examples
androidlistenerpreferenceactivitycheckboxpreference

Is it possible to add long press listener to CheckBoxPreference?


The answers in this thread are not helping in any way.
I have one requirement where I want to do something when user long presses on CheckBoxPreference. I am dynamically creating the CheckBoxPreference inside activity. I am using below piece of code to populate the view:

m_PreferenceScreen = getPreferenceManager().createPreferenceScreen(this);    
m_PreferenceCategory = new PreferenceCategory(this);    
m_CheckBoxPreference = new CheckBoxPreference[m_Cursor.getCount()];
int i = 0;    
while (m_Cursor.moveToNext()) {    
    //Create checkbox instances here    
    m_CheckBoxPreference[i].setOnPreferenceChangeListener(this);     
    m_PreferenceCategory.addPreference(m_CheckBoxPreference[i++]);    
}    
setPreferenceScreen(m_PreferenceScreen);    

On what I am trying to achieve?
I have few entries in database. I want to populate a list of checkboxes corresponding to each entry in database(I am able to do it with above code). Now my requirement is, when user long presses on any checkbox, it should do something(Say, open a dialog box).

Is this thing doable with above piece of code?
I will also appreciate any alternate solution. However, I would prefer going with the first approach.


Solution

  • I managed to do this. The below trick works for me.

    ListView listView = getListView();
    listView.setOnItemLongClickListener(this);
    
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        ListView listView = (ListView) parent;
        ListAdapter listAdapter = listView.getAdapter();
        Object obj = listAdapter.getItem(position);
        if (obj != null && obj instanceof View.OnLongClickListener) {
            View.OnLongClickListener longListener = (View.OnLongClickListener) obj;
            return longListener.onLongClick(view);
        }
        return false;
    }