[英]how to change android button background twice?
這里的代碼
Button change = (Button) findViewById(R.id.btn_change); change.setBackgroundResource(R.drawable.button_red); ... change.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { v.setBackgroundResource(R.drawable.button_orange); try { Thread.sleep(5000, 0); } catch (InterruptedException e) { e.printStackTrace(); } v.setBackgroundResource(R.drawable.button_green); } });
在Android中使用Thread.sleep()
是非常糟糕的做法,尤其是在主UI線程上。 改為使用計時器或post runnables(見下文)。
change.setOnClickListener(new Button.OnClickListener() {
public void onClick(final View v) {
v.setBackgroundResource(R.drawable.button_orange);
Handler handle = new Handler(); // Probably shouldn't create one each time, but here is the idea
handle.postDelayed(new Runnable() {
@Override
public void run() {
v.setBackgroundResource(R.drawable.button_green);
}
}, 5000);
}
});
考慮使用動畫Drawable 。
在你的情況下,你可以像這樣定義你的drawable:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true">
<item android:drawable="@color/red" android:duration="0" />
<item android:drawable="@color/orange" android:duration="5000" />
<item android:drawable="@color/green" android:duration="0" />
</animation-list>
這說,“當它開始播放時開始變紅,立即切換到橙色5秒,然后切換到綠色。”
所以在你的代碼中:
Button change = (Button) findViewById(R.id.btn_change);
// This starts you off red
change.setBackgroundResource(R.drawable.color_animation);
...
change.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
AnimationDrawable ad = (AnimationDrawable) v.getBackground();
// Start the animation, which will switch to orange immediately for 5 seconds, then turn green
ad.start();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.