Frage

I have a ListView that I populate with multiple elements by using the view holder pattern. I have specified a Selector to change the background colour of the selection. When the user has selected an item (or not) and chosen to continue to the next Activity in my control flow, I want to retrieve what he selected and feed it to my business logic.

My dilemma is as follows: When I use methods like AdapterView#getSelectedItem() they return null. What I would require, I think, is to check what item is activated, not selected, but there does not seem to be a method for that. At least not that I can find. If I then proceed to set an OnClickListener in my adapter and override onClick, the Selector will seize to work. I could use methods to set the listview's item to active but then I face the problem of toggling selections; basically what I had wanted to use the Selector in the first place.

Here a bit of code:

persona_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/background_light" android:state_activated="false" />
    <item android:drawable="@android:color/background_light" android:state_pressed="false" />
    <item android:drawable="@android:color/background_dark" android:state_selected="true" />
    <item android:drawable="@android:color/background_dark" android:state_activated="true" />
</selector>

DemoPersonaAdapter.java

@Override
public View getView(int position, View convertView, ViewGroup parentViewGroup)
{       
    final PersonaViewHolder viewHolder;
    final Persona persona = provider[position];

    if (convertView == null)
    {
        convertView = LayoutInflater.from(parentViewGroup.getContext()).inflate(R.layout.list_personas, null);

        viewHolder = new PersonaViewHolder(
                (ImageView) convertView.findViewById(R.id.persona_icon),
                (TextView) convertView.findViewById(R.id.persona_description));
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (PersonaViewHolder) convertView.getTag();
    }

    Bitmap icon = BitmapFactory.decodeResource(parent.getResources(), persona.getPicture());
    viewHolder.setIcon(icon, 50, 50);
    viewHolder.setDescription(persona.getName() + " is a " + persona.getType() + "!");

    convertView.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {   
            ((ParentClass)parent).setPersona(persona);
        }
    });
    return convertView;
}
War es hilfreich?

Lösung

Why not use a global item click listener on the list instead of a per view click listener?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top