Android: How to disable list items on list creation

Viewed 38434

I'm pretty new to Android dev and still working out a lot of things.

I've got a main menu showing using the following code, but can't work out how to disable selected items in the menu. Can anybody help me with some sample code?

public class listTest extends ListActivity {

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setListAdapter(ArrayAdapter.createFromResource(this, R.array.mainMenu,
                android.R.layout.simple_list_item_1)); 
        //not sure how to disable list items here
    }

    protected void onListItemClick(ListView list, View view, int position, long id) {
        // can disable items when they are clicked on
        view.setEnabled(false);
    }   

}

and I have a string-array in my strings.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="mainMenu">
        <item>Item 1</item>
        <item>Item 2</item>
        <item>Item 3</item>
    </string-array> 
</resources>

Thank you

4 Answers

I believe whether a list item is enabled or not is part of that item's state, so I guess you have to manage that in your ListAdapter. When subclassing an adapter, you can override isEnabled(position). For any position you return true here, the ListView will mark this item as disabled.

So what you want to do is something like this:

class MenuAdapter extends ArrayAdapter<String> {

    public boolean isEnabled(int position) {
       // return false if position == positionYouWantToDisable
    }

}

This probably requires e.g. a Map managing the enabled state of each item if you want to be able to enable/disable an item using a setter.

Then set the custom adapter on your ListView.

Related