5

How can I set up the animation when the user selects an element in a listview?

I am making my own listview adapter to set even rows with a pink background and odd rows with a purple background. The only problem is that I am not sure how to set the animation for the user clicking ("touching") an element.

I thought of implementing OnTouchListener and changing the background to green when selected BUT I have buttons inside the rows that might no longer work due to OnTouchListener being implemented. Is this true?

Code:

public class MyAdapter extends BaseAdapter {

    public View getView(int position, View convertView, ViewGroup parent) {
        // position is the element's id to use
        // convertView is either null -> create a new view for this element!
        //                or not null -> re-use this given view for element!
        // parent is the listview all the elements are in    

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.your_layout, null);

            // here you must do whatever is needed to populate the elements of your
            // list element layout
            ...
        } else {
            // re-use the given convert view

            // here you must set all the elements to the required values
        }

        // your drawable here for this element 
        convertView.setBackground(...);

        // maybe here's more to do with the view
        return convertView;
    }
}

1 Answer 1

2

Use a StateListDrawable with a defined item for state_selected.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@drawable/selected" />
    ...Other States...
    <item android:drawable="@drawable/normal" />
</selector>

This way, when the list item is selected it will use that "selected" graphic automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.