我是Android的新手。所以如果我在问一个愚蠢的问题请原谅我。
我的应用程序在线性布局中只包含一个按钮。要求是,我必须改变我的应用程序的线性布局的背景颜色在一个按钮点击。默认情况下,它是白色,当我按下按钮时,它应该会变成一些随机的颜色,当我再次按下按钮时,它应该再次变成默认颜色(白色)。
button.setBackgroundColor(Color.BLUE)
(在OnClick()方法上),将背景颜色更改为蓝色,但如何恢复为默认颜色?
发布于 2016-08-29 14:00:39
在drawble文件夹中创建xml文件
change_colcor.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_focused="true"
android:state_pressed="true"
android:color="#222222" />
<item
android:state_focused="false"
android:state_pressed="true"
android:color="#4aa5d4" />
</selector>
,然后将XML文件设置为按钮背景。
<Button
android:id="@+id/mybutton"
android:background="@drawable/change_colcor" />
发布于 2016-08-29 14:21:13
我希望这段代码能对你有所帮助!单击按钮时获取布尔值变量。
public class MainActivity extends Activity {
boolean iscolor = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
final LinearLayout layout = (LinearLayout) findViewById(R.id.LinearLayout1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if(iscolor)
{
layout.setBackgroundColor(Color.BLUE);
iscolor = false;
}
else
{
layout.setBackgroundColor(Color.WHITE);
iscolor = true;
}
}
});
}
发布于 2016-08-29 14:02:04
创建一个名为button_pressed.xml
的形状,如下所示...
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/blue" />
<stroke
android:width="4dp"
android:color="@color/blue" />
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
</shape>
假设你有两个按钮,它们的id
分别是R.id.btn
和R.id.btn1
,如下所示…
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="12dp"
android:background="@drawable/button_pressed"
android:onClick="onClick"
android:text="Press Me 1" />
</LinearLayout>
将onClick()
方法写为follows...which将允许您在按下另一个按钮之前保留更改的颜色。
Button button;
public void onClick(View v) {
Drawable dr = getResources().getDrawable(R.drawable.button_pressed);
dr.setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.SRC_ATOP);
switch (v.getId()) {
case R.id.btn:
if (button == null) {
button = (Button) findViewById(v.getId());
} else {
button.setBackgroundResource(R.drawable.button_pressed);
button = (Button) findViewById(v.getId());
}
button.setBackgroundDrawable(dr);
break;
default:
break;
}
}
https://stackoverflow.com/questions/39199286
复制相似问题