更改按钮背景一小段时间

时间:2012-08-20 12:32:05

标签: android

按下按钮后,我想在短时间内更改按钮背景颜色。该按钮应在该时间段后重新获得之前的状况。 可能一个处理程序是这个问题的正确决定,遗憾的是我没有找到做类似事情的工作示例。 如果有人能给我一个如何做这样的事情的简短例子我会很感激。

2 个答案:

答案 0 :(得分:3)

这样做:

public class LaunchActivity extends Activity implements OnTouchListener{

private Button yourButton;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        
    setContentView(R.layout.main);      

    yourButton= (Button)findViewById(R.id.yourButton);
    yourButton.setOnTouchListener(this); 

}

@Override
public boolean onTouch(final View view, MotionEvent event) {

final int action = event.getAction();

    if(view.getId()==R.id.yourButton){
        if(action == MotionEvent.ACTION_DOWN)
              yourButton.setBackgroundResource(R.drawable.ic_button_pressed);
        if(action == MotionEvent.ACTION_UP){
               Handler handler = new Handler(); 
               handler.postDelayed(new Runnable() { 
               public void run() { 
              yourButton.setBackgroundResource(R.drawable.ic_button_normal); 
           } 
         }, 2000); 

        }
    }

} }

或使用onClick侦听器:

@Override
public void onClick(View v) {
    yourButton.setBackgroundResource(R.drawable.first_icon);
    // SLEEP 2 SECONDS HERE ...
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
         public void run() { 
              yourButton.setBackgroundResource(R.drawable.second_icon); 
         } 
    }, 2000); 
}

答案 1 :(得分:1)

您可以在res/drawable/button_background

下为您的按钮定义XML背景
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_background_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/button_background_notpressed"/>
</selector> 

并使用ImageButton

<ImageButton
    ...
    android:background="@drawable/button_background"
    ... />