Android RelativeLayout change color onClick

前端 未结 4 591
猫巷女王i
猫巷女王i 2020-12-09 15:53

How do i change the color of a Relative Layout i use as a clickable on Click like the normal Button? Like i want a visual feedback the layout was pressed.

I tried it

相关标签:
4条回答
  • 2020-12-09 16:19

    Try the following steps:

    In res --> values folder create color.xml with the content:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>     
        <color name="black">#000000</color> 
        <color name="white">#ffffff</color>
    </resources>
    

    As <item> tag in selector requires a drawable attribute or child tag defining a drawable, your layout_selector.xml file (which is saved in res --> drawable) should look like this:

    <?xml version="1.0" encoding="utf-8"?> 
    <selector xmlns:android="http://schemas.android.com/apk/res/android">   
        <item android:state_focused="true" android:drawable="@color/black"/> 
        <item android:state_pressed="true" android:state_enabled="false" android:drawable="@color/black" />
        <item android:drawable="@color/white"/> 
     </selector>
    

    Also, as said earlier, the relative layout should be clickable (android:clickable="true")

    and its background set as android:background="@drawable/layout_selector"

    Hope it helps

    0 讨论(0)
  • 2020-12-09 16:27

    Layouts are not displayed into the screen. They only may to conrain views. You shold add some View and then add onClick listener to that view.

    Possible dublicate: Android clickable layout

    0 讨论(0)
  • 2020-12-09 16:27

    put this layout_selector.xml in drawable folder ie(res>drawable>layout_selector.xml) then set android:background="@drawable/layout_selector" instead android:background="@color/layout_selector"

    0 讨论(0)
  • 2020-12-09 16:41

    Use selector on the android:background attribute of your RealtiveLayout. Also make the layout clickable (through android:clickable="true").

    0 讨论(0)
提交回复
热议问题