0

I want to change the background color of a customView when it's pressed and slightly "remove" this background color when the view losses the "pressed-state". However, I googled this question and found a solution using a StateListDrawable. I've tried this within my customView (which is added to a ListView programmatically), but just the "normal color" was set to my view. When I touched the view nothing happens. What's going wrong?

the selector xml-file:

<?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/bckgr" />
    <item 
        android:drawable="@color/transparent" />
</selector>

within the constructor of my custom view:

this.setBackgroundResource(R.drawable.list_item_bckgr);
user2224350
  • 2,262
  • 5
  • 28
  • 54

5 Answers5

0

you have to apply your background to the View the Adapter fills up (the view your getView implementation is returning) not to the ListView self

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
0

Try setting android:descendantFocusability to true on the ListView.

Emil Davtyan
  • 13,808
  • 5
  • 44
  • 66
0

Hey Are you making the view focussable and clickable, use in the constructor:

setClickable(true);
setFocusable(true);

May be your view isn't getting focus.

Gaurav Vashisth
  • 7,547
  • 8
  • 35
  • 56
0

You need to set the OnTouchListener to handle touch events. When the view is touched, change the background, and when the view is 'untouched', change the background back to the original.

To set the listener, call the View.setOnTouchListener() function of your custom view with the OnTouchListener you create to handle these events.

Here is the reference to OnTouchListener:

http://developer.android.com/reference/android/view/View.OnTouchListener.html

tbkn23
  • 5,205
  • 8
  • 26
  • 46
0

I imagine that you have an override method to the OnTouch() method, what I would do is create an instance variable (class var) that would hold the image that you want to have as a background, and set it in your OnTouch() method. Then, Override your OnDraw() method which would give you a reference to the canvas, and use the canvas.DrawBitmap() to draw your background.

This answer shows you more details on how to draw the bitmap Setting background image in a custom view

Community
  • 1
  • 1
Has AlTaiar
  • 4,052
  • 2
  • 36
  • 37