8

I'm trying to assing a color selector to an extended class of LinearLayout, so, i think its like if we speak about linearLayout.

i followed the instructions on this post, the answer talking about shapes.

Now i have 3 xml on drawables folders:

normal.xml file

<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle" >
  <solid android:color="#ffffffff" />
</shape>

pressed.xml file

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
   <solid android:color="#00000000" />
</shape>

and finally, bg.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="@drawable/pressed" />
    <item android:state_focused="true" android:drawable="@drawable/pressed" />
    <item android:state_selected="true" android:drawable="@drawable/pressed" />
    <item android:drawable="@drawable/normal" />
</selector>

I am accessing this in the following way:

    Drawable d = getResources().getDrawable(context.getResources().getIdentifier("mypackageuri.tProject:drawable/bg", null, null));
    view.setBackgroundDrawable(d);

The "normal" state its fine, with the color set at "normal.xml", but no way with the other ones, I press my view and nothing happens, it's not changing color in any way...

I can't see what i'm doing wrong...

Thank you

Community
  • 1
  • 1
Deitools
  • 421
  • 6
  • 16
  • 1
    might want to paste your layout xml – azharb Jul 28 '11 at 21:17
  • 6
    Whoa that has to be the most roundabout way of getting a drawable resource. Instead of `getResources().getDrawable(context.getResources().getIdentifier("mypackageuri.tProject:drawable/bg", null, null));` try `getResources().getDrawable(R.drawable.bg);` . Unless I'm missing something. – dmon Jul 28 '11 at 21:38
  • @dmon good point, ill try that too! thanks!! – Deitools Jul 29 '11 at 08:31
  • if somebody wants to get full solution, check this repository: https://github.com/shamanland/AndroidLayoutSelector there is custom clickable/checkable ```LinearLayout``` like a ```ToggleButton``` – Oleksii K. Oct 17 '13 at 12:22

1 Answers1

22

Your view needs to be clickable in order to get the state pressed when you click on it. Use :

    view.setClickable(true);

or in the layout xml :

    android:clickable="true"
Paul Lammertsma
  • 37,593
  • 16
  • 136
  • 187
Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84