在框内垂直向上和向下移动按钮

时间:2016-12-20 12:31:09

标签: java android

我能够在SliderButton-RED之上获得一个按钮Background Slider并在屏幕上移动。如何告诉它只在框Background Slider-GREEN)内上下移动?所以,检查一些约束(限制)。

我的代码:

public class Slider extends RelativeLayout implements View.OnTouchListener {
private Context context;
private ImageView backgroundSlider;
private ImageView sliderButton;
float xx = 0;
float yy = 0;
private float xDelta;
private float yDelta;
Thread thread;

public Slider(Context context) {
    super(context);
    this.context = context;
    initSlider();

    if(sliderButton != null) {
        sliderButton.setOnTouchListener(this);
    }
}

public ImageView setView ( String imageName) {

    ImageView image = new ImageView(context);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
    image.setLayoutParams(layoutParams);

    // load image
    try {
        // get input stream
        InputStream ims = getContext().getAssets().open(imageName);
        // load image as Drawable
        Drawable d = Drawable.createFromStream(ims, null);
        // set image to ImageView
        image.setImageDrawable(d);
    } catch (IOException ex) {


    }

    return image;
}

public void initSlider() {

    backgroundSlider = setView("slider_base@3.png");
    sliderButton = setView("slider_button@3x.png");

    addView(backgroundSlider);
    addView(sliderButton);

}

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

    final float x = motionEvent.getRawX();
    final float y = motionEvent.getRawY(); 

    switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:

            xDelta = view.getX() - x;
            yDelta = view.getY() - y;

            break;

        case MotionEvent.ACTION_UP:

            view.setX(xx);
            view.setY(yy);

            break;

        case MotionEvent.ACTION_POINTER_DOWN:
            break;

        case MotionEvent.ACTION_POINTER_UP:
            break;

        case MotionEvent.ACTION_MOVE:

            final float transX = (float) x;
            final float transY = (float) y;

            thread = new Thread() {
                @Override
                public void run() {

                    sliderButton.setX(transX + xDelta);
                    sliderButton.setY(transY + yDelta);

                    }

            };
            thread.start();

            break;

    }

    return true;
  }
}

图像:

enter image description here

感谢您的任何建议!

0 个答案:

没有答案