2014-04-03 91 views
0

所以我用3个按钮制作应用程序。目前我有以下的.xml文件,使他们有四舍五入的边缘和红色的颜色。现在我想让它们如此,如果选择了一个,那么该按钮会变成绿色,而另外两个保持不变,或者变回红色。我怎么能这样做呢?我必须制作另一个.xml文件吗? 下面是我的按钮绘制.xml文件:选择一个按钮时更改按钮的颜色; Android开发

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" android:padding="10dp"> 
    <!--red colour.--> 
    <solid android:color="#FF0000"/> 
    <corners 
     android:bottomRightRadius="10dp" 
     android:bottomLeftRadius="10dp" 
     android:topLeftRadius="10dp" 
     android:topRightRadius="10dp"/> 
    <stroke android:width="2px" android:color="#000000"/> 
</shape> 
+0

是的,你需要写不同的可绘制的不同的固体和笔画颜色。 –

+1

我会用3 RadioButtons RadioGrop,而不是**保持按下状态**(按钮状态是瞬间的)。您可以删除按钮图形,并使用红/绿状态的自定义选择器作为背景 –

回答

2

使用selector如下:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <!-- green state --> 
    <item 
     android:drawable="@drawable/button_selected" 
     android:state_selected="true"></item> 
    <!-- green state --> 
    <item 
     android:drawable="@drawable/button_pressed" 
     android:state_pressed="true"></item> 
    <!-- red state --> 
    <item 
     android:drawable="@drawable/button_disabled"></item> 

</selector> 

然后,你应该把这种选择,如:

<Button 
    ... 
    android:background="@drawable/my_selector" /> 

,创造每个drawable.xml(作为红色按钮的示例):button_selected,button_pressed and button_disabled

您还可以通过使用onTouchListener等残留状态:

button.setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     switch (event.getAction()) { 
      case MotionEvent.ACTION_DOWN: 
       // change the color 
       return true; 
      case MotionEvent.ACTION_UP: 
       // intitial color 
       return true; 
      default: 
       return false; 
     } 
    } 
}); 

然而,最好使用Selectorbackground,这种使用较少的资源。


UPDATE:

可以使用setBackgroundResource方法来保持和改变点击按钮的背景状态如下:

// 1st clicklistener method 
button.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     v.setBackgroundResource(R.drawable.green_drawable); 
     button2.setBackgroundResource(R.drawable.selector_drawable); 
    } 
} 

// 2nd clicklistener method 
button2.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     v.setBackgroundResource(R.drawable.green_drawable); 
     button1.setBackgroundResource(R.drawable.selector_drawable); 
    } 
} 

未经测试,但它应该工作。

+0

Hi @ theGuy05,它不起作用,这不是您要查找的内容吗? – Fllo

+0

好的,非常感谢!现在他们会成为一种让按钮在点击后保持绿色的方式吗?那么当另一个按钮被点击时,该按钮会变成绿色?像单选按钮,但不使用单选按钮。 – theGuy05

+0

@ theGuy05我更新了我的答案,我没有测试这个,但这应该可以做到。让我知道它是否工作。 HTH – Fllo