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 に答える