I’m working on an Android app and need help with a custom listview. I want it to work like the one in the Gmail app. Here’s what I’m trying to do:
- Each row has a picture on the left and some text on the right
- Tapping the picture selects the row
- Tapping anywhere else on the row opens the item
I’ve got most of it working, but I’m stuck on one part. When you tap the row to open an item, it doesn’t highlight like it should. Here’s a bit of my code:
@Override
public View getCustomRow(int spot, View oldView, ViewGroup parentView) {
View newRow = super.getCustomRow(spot, oldView, parentView);
pictureBox.setOnTapListener(new View.OnTapListener() {
@Override
public void onTap(View v) {
getMyList().setRowChecked(spot, !getMyList().isRowChecked(spot));
}
});
newRow.setOnTapListener(new View.OnTapListener() {
@Override
public void onTap(View v) {
showMessage(getActivity(), "Row " + spot + " tapped", QUICK_POPUP);
}
});
}
Any ideas on how to make the row highlight when tapped? Thanks!
To achieve the desired highlighting effect when tapping a row, you might want to consider using a StateListDrawable for your row layout. This allows you to define different background states, including a ‘pressed’ state.
First, create a selector XML in your drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/row_pressed" />
<item android:drawable="@android:color/transparent" />
</selector>
Then, set this as the background for your row layout. In your adapter, you can use the setBackgroundResource method to apply the selector. This approach provides a clean separation between UI and logic, and should resolve your highlighting issue without complicating your existing code structure.
I’ve encountered a similar issue when working on a custom listview for a client project. In my experience, the problem was due to the default ListView behavior interfering with custom tap listeners. One solution that worked for me was to override the ListView’s onItemClickListener instead of setting tap listeners on each row. In the onItemClick method, I checked where the tap occurred and used the ListView’s setItemChecked method for selection, while relying on a selector drawable for proper highlighting.
This method centralizes the click handling and offers more precise control over row interactions. Testing on different Android versions is also important, as ListView behavior can vary.
hey ryan, I’ve dealt with this before. try adding android:background=“@drawable/your_selector” to ur row layout XML. create a selector drawable with different states (normal, pressed). this should give u that highlight effect when tapped. also make sure ur not overriding the default listview behavior accidentally in ur code. good luck!