Android LinearLayout with color resource: What am I doing wrong?

后端 未结 2 502
感动是毒
感动是毒 2020-11-27 13:40

I followed this tutorial to create a color state list for a particular Android view. I just want it to highlight when clicked so the user knows why the screen just changed.

相关标签:
2条回答
  • 2020-11-27 13:51

    I remember that I worked around this error by using state drawable instead of state color. For some reason layout background just doesn't work with stateful colors. So try creating a stateful drawable (for example list of shape drawables with different colors) and use it as background.

    res/drawable/pressed.xml:

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

    res/drawable/normal.xml:

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

    res/drawable/background.xml:

    <?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:drawable="@drawable/normal" />
    </selector>
    

    Then use background.xml drawable as background :)

    0 讨论(0)
  • 2020-11-27 14:09

    Instead of using shapes in your drawable, you can use the android:drawable attribute which accepts a color resource (e.g. @color/black).

    layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/myview"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:background="@drawable/myDrawable">
        <!-- other views in layout-->
    </LinearLayout>
    

    my_drawable.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <!-- focused -->
        <item android:state_focused="true" android:drawable="@color/YOUR_COLOR_HERE" />
        <!-- focused and pressed-->
        <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/YOUR_COLOR_HERE" />
        <!-- pressed -->
        <item android:state_pressed="true" android:drawable="@color/YOUR_COLOR_HERE" />
        <!-- default -->
        <item android:drawable="@color/YOUR_COLOR_HERE" /> 
    </selector>
    

    In my_drawable.xml you need to make sure that the colors you specify are defined in res/values/colors.xml, or this won't work.

    If you want to use an image instead of a color change from a color resource to a drawable resource. Example:

    android:drawable="@color/YOUR_COLOR_HERE"
    android:drawable="@drawable/YOUR_IMAGE_HERE"
    
    0 讨论(0)
提交回复
热议问题