0

これが私のコードです

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Button;

public class MyLongPressCustomButton extends Button{

    private InStock instock;

    public MyLongPressCustomButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyLongPressCustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyLongPressCustomButton(Context context) {
        super(context);
    }

    public void setSampleLongpress(InStock sl) {
        instock = sl;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        cancelLongpressIfRequired(event);
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onTrackballEvent(MotionEvent event) {
        cancelLongpressIfRequired(event);
        return super.onTrackballEvent(event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
                || (keyCode == KeyEvent.KEYCODE_ENTER)) {
            cancelLongpress();
        }
        return super.onKeyUp(keyCode, event);
    }

    private void cancelLongpressIfRequired(MotionEvent event) {
        if ((event.getAction() == MotionEvent.ACTION_CANCEL)
                || (event.getAction() == MotionEvent.ACTION_UP)) {
            cancelLongpress();
        }
    }

    private void cancelLongpress() {        
        if (instock != null) {
            instock.cancelLongPress();
        }
    }    
}

マルチクラスに使用する必要がありますが、現在は InStock クラスのみです。マルチクラスのコードを変更するにはどうすればよいですか? InStock を Activity に変更したときに cancelLongpress() メソッドが未定義です。

前もって感謝します :)

4

1 に答える 1

1

この場合、デリゲートパターンを使用する必要があります。

  public interface MyDelegate{
      void cancelLongPress();
  }

次に、このデリゲートをカスタムボタンに使用します

 public class MyLongPressCustomButton extends Button{
      MyDelegate delegate;

      public MyLongPressCustomButton (MyDelegate delegate){
          this.delegate = delegate;
      }

      private void cancelLongpress() {        
        if (null  != delegate) {
            delegate.cancelLongPress();
        }
     }              
 }

これを多くのクラスで使用する場合は、このインターフェイスを実装するだけです。例えば

  public class YourActivity extend Activity implements MyDelegate{
      @override  
      void oncreate(){
           //create new button with a delegate
        MyLongPressCustomButton btn = new  MyLongPressCustomButton(this);
         //do something
      }

      //real work is here
      @override  
      public void cancelLongPress(){

      }
  }
于 2012-08-02T05:16:46.773 に答える