2014-04-13 59 views
0
<Button 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     android:text="Add" 
     android:id="@+id/btnAdd" 
     android:background="#ff6347" 
     android:textColor="#f8f8f8" 
     android:layout_marginTop="36dp" 
     android:clickable="true" 
     android:layout_below="@+id/txtAddress" 
     android:layout_centerHorizontal="true" 
     android:focusable="true" /> 

这是我的XML Button元素,它很好,很花哨......但我希望它在被按下时被知道。我怎么能让它有不同的样式,当按下时,与没有按下时?更改<Button>颜色onClick?

回答

0

你想用一个选择作为背景的按钮。基本上,您可以为按钮的每种状态定义所需的不同形状,并且形状由颜色,圆角半径和其他很酷的东西组成。保存在RES /绘制/ button.xml

XML文件:

<?xml version="1.0" encoding="utf-8"?> 
    <selector xmlns:android="http://schemas.android.com/apk/res/android"> 
     <item android:state_pressed="true"> <!-- pressed --> 
      <shape android:shape="rectangle" > 
       <solid android:color="@color/blue" /> 
      </shape> 
     </item> 
     <item> <!-- default --> 
      <shape android:shape="rectangle" > 
       <solid android:color="@color/red" /> 
      </shape> 
     </item> 
    </selector> 

这种布局XML应用状态列表绘制到按钮:

<Button 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    android:background="@drawable/button" /> 
+0

'机器人:drawable'。引用文档 **可绘制资源。需要。引用一个可绘制的资源**,并且在你的示例选择器中没有一个 – Raghunandan

+0

正在编辑,对那个好先生感到抱歉。 – tambykojak