Android ListView Select Animation
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 purpl开发者_运维技巧e 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;
}
}
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.
精彩评论