1

我想在按下按钮后的短时间内更改按钮背景颜色。在那段时间之后,按钮应该恢复到以前的状态。对于这个问题,处理程序可能是正确的决定,不幸的是我没有找到做类似事情的工作示例。如果有人能给我一个简短的例子来说明如何做这样的事情,我将不胜感激。

4

2 回答 2

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); 
}
于 2012-08-20T12:47:07.900 回答
1

您可以在下面为您的按钮定义一个 XML 背景res/drawable/button_background

<?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"
    ... />
于 2012-08-20T12:36:44.750 回答