Search code examples
androidandroid-listviewandroid-appwidget

Create a ListView of CheckedTextView elements where the first element is editable


I have a configuration activity for an AppWidget. I want to let the user choose an existing string for the widget, or create one of their own by selecting the first option and editing the text within the list.

How do I change the element type of just the first list item to a different type of view that will allow users to insert custom text?


Solution

  • The ListAdapter interface has two methods getViewTypeCount() and getItemViewType(). So in your case, they might be implemented like this:

    @Override
    public int getViewTypeCount() {
        return 2;
    }
    
    @Override
    public int getItemViewType(int position) {
        // first position has view type == 0; all others have view type == 1
        return position == 0 ? 0 : 1;
    }
    

    What this does is make sure that the correct views are recycled for the correct positions. Once you have these methods, then you can do:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (position == 0) {
            // create a custom edit view and return it
        } else {
            // create a selection view and return it
        }
    }