2013-07-18 299 views
0

---在android应用---如何将按钮背景颜色更改为点击操作?

点击一个按钮后,它的背景颜色被更改为required。如再次点击,其颜色将恢复原来的颜色。

如何实现它?

任何回应,谢谢!

============================================== ==================================== 更新:从网络,我找到一种方法来实现这一目标。 设计一个可绘制颜色在这样的XML:

<drawable name="button_checked">#ffff0000</drawable> 
活性

,使用下面的代码来获得可绘制对象:

Resources resource = getBaseContext().getResources(); 
checked_drawable = resource.getDrawable(R.drawable.button_checked); 
中的onClick功能

,根据一个布尔变量:

setBackgroundDrawable(checked_mDrawable) 

设置按钮背景。

+0

[用不同的颜色标准的Android按钮](http://stackoverflow.com/questions/1521640/standard-android-button-with-a-different-color)的可能重复 – fvrghl

回答

0

在你的js文件把

$( '#按钮')toggleClass( 'BG')。

在你的CSS

,有你的常规按钮css样式

#button { background: white; } 

然后添加

#button.bg { background: red; } 

所以,当他们点击按钮,它会变成红色背景,如果他们再次点击它,它会变回白色。

使用任何颜色/网址你想要的背景。

+0

谢谢您的回复!我在android应用程序中使用java,那么如何实现它? – ooper

0

你只需要像下面创建a state list drawable resource

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item android:drawable="@drawable/btn_login_pressed" android:state_pressed="true"/> 
    <item android:drawable="@drawable/btn_login_normal" android:state_pressed="false"/> 

</selector> 

更新时间: 也许你想为单选按钮的效果,下面是一个例子:

<RadioButton 
     android:id="@+id/tab_communication" 
     android:layout_width="wrap_content" 
     android:layout_height="40dp" 
     android:layout_weight="1" 
     android:background="@null" 
     android:button="@null" 
     android:drawableTop="@drawable/category_communication" 
     android:paddingBottom="5dp" 
     android:paddingTop="5dp" /> 

绘制/ category_communication.xml :

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item android:drawable="@drawable/category_communication_checked" android:state_checked="true"/> 
    <item android:drawable="@drawable/category_communication_normal" android:state_checked="false"/> 

</selector> 

ToggleButton是另一种选择。

+0

我刚测试过你的方法。但它显示的不是我希望的。 – ooper

+0

我刚测试过你的方法。但它显示的不是我希望的。我想要的是当按钮被点击时,其背景颜色被改变以保持颜色A.当我再次点击它时,其背景颜色改变以恢复原始颜色。 – ooper

+0

我已经更新了我的答案,请参阅更新, – Ivan

0

你可以在代码中动态执行它(我不知道如何在xml中配置它)。

boolean flag=true; 
Button button=(Button)findViewById(R.id.button); 
oncreate() 
{ 
    button.setBackgroundResource(R.drawable.first_time_click); 
    button.setOnClickListener(new OnClickListener() 
    { 
    public void onClick(View v) 
    { 
     if (flag) 
     { 
      button.setBackgroundResource(R.drawable.odd_time_click);   
     }else 
     { 
      button.setBackgroundResource(R.drawable.even_time_click); 
     } 
     flag=!flag; 
    } 
    }); 
} 
相关问题