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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With