How to take View and layout on the screen? - android

I try to make a activity and a View on the screen, cause the activity have the buttons which I need. My question is how can I do it, that when I start the app I see the buttons from the activity and the ball and the box from the view class??
How should I take the view in the layout?
that is the activity:
public class GameView extends Activity implements OnClickListener {
private Button bPAUSE;
private TextView tvTries;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameview);
initialize();
}
public void onClick(View v) {
}
public void initialize(){
bPAUSE = (Button) findViewById(R.id.button1);
bPAUSE.setOnClickListener(this);
tvTries = (TextView) findViewById(R.id.textView1);
}
}
that the View class:
public class BouncingBallView extends View {
private Ball ball;
private Box box;
// For touch inputs - previous touch (x, y)
private float previousX;
private float previousY;
// Constructor
public BouncingBallView(Context context) {
super(context);
box = new Box(0xff00003f); // ARGB
ball = new Ball(Color.GREEN);
// To enable keypad
this.setFocusable(true);
this.requestFocus();
// To enable touch mode
this.setFocusableInTouchMode(true);
}
// Called back to draw the view. Also called after invalidate().
#Override
protected void onDraw(Canvas canvas) {
// Draw the components
box.draw(canvas);
ball.draw(canvas);
// Update the position of the ball, including collision detection and reaction.
ball.moveWithCollisionDetection(box);
// Delay
try {
Thread.sleep(30);
} catch (InterruptedException e) { }
invalidate(); // Force a re-draw
}
// Called back when the view is first created or its size changes.
#Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
// Set the movement bounds for the ball
box.set(0, 0, w, h);
}
int touchCounter = 2;
#Override
public boolean onTouchEvent(MotionEvent event) {
float currentX = event.getX();
float currentY = event.getY();
float deltaX, deltaY;
float scalingFactor = 1.0f / ((box.xMax > box.yMax) ? box.yMax : box.xMax);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchCounter = 2;
if (currentX >= previousX) {
deltaX = currentX - previousX;
ball.speedX += deltaX * scalingFactor;
} else if (previousX >= currentX) {
deltaX = previousX - currentX;
ball.speedX += deltaX * scalingFactor;
} if (currentY >= previousY) {
deltaY = currentY - previousY;
ball.speedX += deltaY * scalingFactor;
} else if (previousY >= currentY) {
deltaY = previousY - currentY;
ball.speedY += deltaY * scalingFactor;
}
//vorherig(previous) - aktuell
break;
case MotionEvent.ACTION_UP:
touchCounter = 1;
// Modify rotational angles according to movement
break;
}
// Save current x, y
previousX = currentX;
previousY = currentY;
return true; // Event handled
}
}
I actually tries to do this in the activity class but the layout is missing...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View BouncingBallView= new BouncingBallView(this);
setContentView(BouncingBallView);
initialize();
}

Related

create a custom view canvas that draws a collection of custom moveable Rect views

I'm having trouble figuring out how to get a dynamic collection of custom views to display as movable rectangles inside a canvas. The canvas is a bar with bar stools and I want the restaurant manager to be able to create the layout of his/her bar that other pages can utilize.
I have it working, but not well and the individual "BarSpots" won't move and the onTouchEvent of the ViewBarSpot isn't firing - however - the onTouchEvent of the ViewBarCanvas IS firing. What am I missing??
ActivityBarLayout:
private FrameLayout flCanvas;
List<BarSpot> dbBarSpots;
...
private void LoadBar(List<BarSpot> barSpots) {
try{
flCanvas.removeAllViews();
View viewBarCanvas = new ViewBarCanvas(getApplicationContext(), barSpots);
flCanvas.addView(viewBarCanvas);
}
catch(Exception e){
LogUtil.log(e.getMessage());
}
}
ViewBarCanvas:
Context mContext;
public List<ViewBarSpot> mBoxs;
public List<BarSpot> mBarSpots;
public ViewBarCanvas(Context context, List<BarSpot> barSpots) {
super(context);
mContext = context;
mBarSpots = barSpots;
mBoxs = new ArrayList<>();
for (BarSpot barSpot : barSpots) {
mBoxs.add(new ViewBarSpot(context, barSpot));
}
init(null);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (ViewBarSpot viewBarSpot : mBoxs) {
canvas.drawRect(viewBarSpot.mRectangle, viewBarSpot.mPaintBackground);
canvas.drawRect(viewBarSpot.mRectangle, viewBarSpot.mStrokePaint);
canvas.drawText(viewBarSpot.mText, viewBarSpot.mStart, viewBarSpot.mStart + viewBarSpot.mNumberOfCharacters, viewBarSpot.mRectangle.exactCenterX(), viewBarSpot.mRectangle.exactCenterY(), viewBarSpot.mPaintText);
}
}
ViewBarSpot:
public float mPosX;
public float mPosY;
public float mLastTouchX;
public float mLastTouchY;
#Override
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
switch (event.getAction() & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN: {
// Remember where we started
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_MOVE: {
// Calculate the distance moved
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
// Move the object
if (mRectangle.left < x && mRectangle.right > x && mRectangle.top < y && mRectangle.bottom > y) {
mPosX += dx;
mPosY += dy;
// Invalidate to request a redraw
postInvalidate();
}
// Remember this touch position for the next move event
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_UP:
/*realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
mBarSpot.setPositionLeft((int)mPosX - SQUARE_SIZE/2);
mBarSpot.setPositionRight((int)mPosX + SQUARE_SIZE/2);
mBarSpot.setPositionTop((int)mPosY - SQUARE_SIZE/2);
mBarSpot.setPositionBottom((int)mPosY + SQUARE_SIZE/2);
}
});*/
}
postInvalidate();
return true;
}
public ViewBarSpot(Context context, BarSpot barSpot) {
super(context);
mContext = context;
mBarSpot = barSpot;
mText = barSpot.getDescription();
mRectangle = new Rect(mBarSpot.getPositionLeft(), mBarSpot.getPositionTop(), mBarSpot.getPositionLeft() + SQUARE_SIZE, mBarSpot.getPositionTop()+ SQUARE_SIZE);
mPaintBackground = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintBackground.setColor(mContext.getResources().getColor(R.color.themeColor1));
mPaintBackground.setStyle(Paint.Style.FILL);
mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mStrokePaint.setStyle(Paint.Style.STROKE);
mStrokePaint.setColor(mContext.getResources().getColor(R.color.themeColor3));
mStrokePaint.setStrokeWidth(2);
mPaintText = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintText.setColor(mContext.getResources().getColor(R.color.themeColor3));
mPaintText.setTextSize(TEXT_SIZE);
mPaintText.setTextAlign(Paint.Align.CENTER);
mNumberOfCharacters = mPaintText.breakText(mText,true, SQUARE_SIZE,null);
mStart = (mText.length()- mNumberOfCharacters)/2;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}

Using Rebound API with ImageView

I am currently in need of making ChatHeads like Facebook. Following the tutorials I found, I can make a ChatHead start from Service. However, when I added Rebound API from Facebook to make it smooth, I created a customized view like this post: Adding natural dragging effect to ImageView same as Facebook Messanger chat heads using Rebound library ;
but it seems to block every background touch. I can only drag the ChatHead around without able to touch anything else. How can I make a ChatHead that is still smooth draggable and also can interact with the background also (just the same as Facebook)? Any help is appreciated.
Thanks in advanced
BTW, this is my view
class ChatHeadView extends View implements SpringListener, SpringSystemListener {
private Spring xSpring;
private Spring ySpring;
private SpringSystem springSystem;
private final SpringConfig COASTING;
private float x;
private float y;
private boolean dragging;
private float radius = 100;
private float downX;
private float downY;
private float lastX;
private float lastY;
private VelocityTracker velocityTracker;
private float centerX;
private float centerY;
int screenWidth, screenHeight;
private Paint mPaint = new Paint();
private Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
public ChatHeadView(Context context, int width, int height) {
super(context);
springSystem = SpringSystem.create();
springSystem.addListener(this);
COASTING = SpringConfig.fromOrigamiTensionAndFriction(0, 0.5);
COASTING.tension = 0;
xSpring = springSystem.createSpring();
ySpring = springSystem.createSpring();
xSpring.addListener(this);
ySpring.addListener(this);
getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
centerX = getWidth() / 2f;
centerY = getHeight() / 2f;
xSpring.setCurrentValue(centerX).setAtRest();
ySpring.setCurrentValue(centerY).setAtRest();
getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
}
});
screenWidth = width;
screenHeight = height;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mBitmap, x - mBitmap.getWidth() / 2,
y - mBitmap.getHeight(), mPaint);
}
#SuppressLint("Recycle")
#Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getRawX();
float touchY = event.getRawY();
boolean ret = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = touchX;
downY = touchY;
lastX = downX;
lastY = downY;
velocityTracker = VelocityTracker.obtain();
velocityTracker.addMovement(event);
if (downX > x - radius && downX < x + radius && downY > y - radius
&& downY < y + radius) {
dragging = true;
ret = true;
}
break;
case MotionEvent.ACTION_MOVE:
if (!dragging) {
break;
}
velocityTracker.addMovement(event);
float offsetX = lastX - touchX;
float offsetY = lastY - touchY;
xSpring.setCurrentValue(xSpring.getCurrentValue() - offsetX)
.setAtRest();
ySpring.setCurrentValue(ySpring.getCurrentValue() - offsetY)
.setAtRest();
checkConstraints();
ret = true;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (!dragging) {
break;
}
velocityTracker.addMovement(event);
velocityTracker.computeCurrentVelocity(1000);
dragging = false;
ySpring.setSpringConfig(COASTING);
xSpring.setSpringConfig(COASTING);
downX = 0;
downY = 0;
xSpring.setVelocity(velocityTracker.getXVelocity());
ySpring.setVelocity(velocityTracker.getYVelocity());
ret = true;
}
lastX = touchX;
lastY = touchY;
return ret;
}
#Override
public void onSpringUpdate(Spring s) {
x = (float) xSpring.getCurrentValue();
y = (float) ySpring.getCurrentValue();
invalidate();
}
#Override
public void onSpringActivate(Spring s) {
}
#Override
public void onSpringAtRest(Spring s) {
}
#Override
public void onSpringEndStateChange(Spring s) {
}
#Override
public void onBeforeIntegrate(BaseSpringSystem springSystem) {
}
#Override
public void onAfterIntegrate(BaseSpringSystem springSystem) {
checkConstraints();
}
private void checkConstraints() {
if (x + radius >= screenWidth) {
xSpring.setVelocity(-xSpring.getVelocity());
xSpring.setCurrentValue(xSpring.getCurrentValue()
- (x + radius - screenWidth), false);
}
if (x - radius <= 0) {
xSpring.setVelocity(-xSpring.getVelocity());
xSpring.setCurrentValue(xSpring.getCurrentValue() - (x - radius),
false);
}
if (y + radius >= screenHeight) {
ySpring.setVelocity(-ySpring.getVelocity());
ySpring.setCurrentValue(ySpring.getCurrentValue()
- (y + radius - screenHeight), false);
}
if (y - radius <= 0) {
ySpring.setVelocity(-ySpring.getVelocity());
ySpring.setCurrentValue(ySpring.getCurrentValue() - (y - radius),
false);
}
}
}
this is where I add View with WindowManager:
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
chatHeadView = new ChatHeadView(this, screenWidth, screenHeight);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, PixelFormat.TRANSLUCENT);
windowManager.addView(chatHeadView, params);
In the documentation WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
Window flag: even when this window is focusable (its FLAG_NOT_FOCUSABLE is not set), allow any pointer events outside of the window to be sent to the windows behind it. Otherwise it will consume all pointer events itself, regardless of whether they are inside of the window.
It's saying about your problem.
Instead, try WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE flag.
you can get TouchEvent on the view and it won't consume other events.

Click event on moving a image

I have an image(ball) its a BitmapDrawable and it moves in all directions on the screen for that i am taking onDraw(canvas) in AnimatedView.java its working fine.
My Requirement:
I want to click on the image, but unfortunately the whole screen takes the event.
Please help me.
How to get click event only on the image?
So that i can proceed with further development.
Here is the code:
MainActivity
public class MainActivity extends Activity {
Context context;
int count=0;
EditText text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnimatedView animatedView=(AnimatedView) findViewById(R.id.anim_view);
animatedView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText text=(EditText) findViewById(R.id.editText1);
ImageView imageView=(ImageView) findViewById(R.drawable.ball);
v.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.animation));
}
});
animatedview.java:
public class AnimatedView extends ImageView{
private Context mContext;
int x = -1;
int y = -1;
private int xVelocity = 10;
private int yVelocity = 5;
private Handler h;
private final int FRAME_RATE = 30;
BitmapDrawable ball;
public AnimatedView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
h = new Handler();
}
private Runnable r = new Runnable() {
#Override
public void run() {
invalidate();
}
};
#Override
protected void onDraw(Canvas c) {
BitmapDrawable ball = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.ball);
if (x<0 && y <0) {
x = this.getWidth()/2;
y = this.getHeight()/2;
} else {
x += xVelocity;
y += yVelocity;
if ((x > this.getWidth() - ball.getBitmap().getWidth()) || (x < 0)) {
xVelocity = xVelocity*-1;
}
if ((y > this.getHeight() - ball.getBitmap().getHeight()) || (y < 0)) {
yVelocity = yVelocity*-1;
}
}
c.drawBitmap(ball.getBitmap(), x, y, null);
h.postDelayed(r, FRAME_RATE);
}
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#000000">
<com.example.example.AnimatedView
android:id="#+id/anim_view"
android:layout_width="fill_parent"
android:layout_height="420dp"
android:onClick="imageClicked" />
</LinearLayout>
**I hope This codes Works for you, what you are looking for.....**
This is the complete code representing both ball movement and touch on ball.
public class MainActivity extends Activity implements OnTouchListener
{
BubbleGraphic bubbleGraphic;
int bm_x = 0, bm_y = 0, bm_offsetx, bm_offsety, bm_w, bm_h, subBM_w, subBM_h;
int f = 0;
private float x, y;
Canvas canvas;
boolean dm_touched = false;
static int random_x;
static int random_y;
boolean touching;
// These variable for position in x_axis direction
int w1;
// These variable for position in y_axis direction
int h1;
// These variable for velocity in x_axis direction
private int w1_V;
// These variable for velocity in y_axis direction
private int h1_V;
Bitmap mainBG;
Bitmap bmpBall;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bubbleGraphic = new BubbleGraphic(this);
bubbleGraphic.setOnTouchListener(this);
// Your Background Image of Canvas
mainBG = BitmapFactory.decodeResource(getResources(), R.drawable.bg1);
w1 = -1;
h1 = -1;
w1_V = 1;
h1_V = 1;
// This is used to create bitmap object and decode the input stream into bitmap
bmpBall = BitmapFactory.decodeResource(getResources(),
R.drawable.myBall);
bm_w = bmpBall.getWidth();
bm_h = bmpBall.getHeight();
setContentView(bubbleGraphic);
}
protected void onPause() {
super.onPause();
bubbleGraphic.pause();
}
protected void onResume() {
super.onResume();
bubbleGraphic.resume();
}
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
x = event.getX();
y = event.getY();
touching = true;
if (dm_touched) {
w1 = (int) x - bm_offsetx;
h1 = (int) y - bm_offsety;
}
break;
case MotionEvent.ACTION_DOWN:
x = event.getX();
y = event.getY();
touching = true;
// checking if Ball is touched
if ((x > w1) && (x < bm_w + w1) && (y > h1) && (y < bm_h + h1)) {
bm_offsetx = (int) x - w1;
bm_offsety = (int) y - h1;
}
dm_touched = true;
break;
case MotionEvent.ACTION_UP:
default:
dm_touched = false;
touching = false;
}
return true;
}
// **************************************************************************************//
// Creating Canvas graphic Class and running thread //
// *************************************************************************************//
class BubbleGraphic extends SurfaceView implements Runnable {
SurfaceHolder holder;
Thread thread = null;
boolean isRunning = false;
boolean holdingBubble = true;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public BubbleGraphic(Context context) {
super(context);
holder = getHolder();
}
public void pause() {
isRunning = false;
while (true) {
try {
thread.join();
} catch (Exception e) {
}
break;
}
thread = null;
}
public void resume() {
isRunning = true;
thread = new Thread(this);
thread.start();
}
public void run() {
while (isRunning) {
if (!holder.getSurface().isValid())
continue;
canvas = holder.lockCanvas();`enter code here`
canvas.drawBitmap(mainBG, 0, 0, null);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(Color.TRANSPARENT);
if (touching) {
canvas.drawRect(x, y, x + bm_w, y + bm_h, paint);
}
canvas.drawBitmap(bmpBall, w1, h1, null);
// Method Responsible for ball movement and its position
checkBallMovementAndPosition();
holder.unlockCanvasAndPost(canvas);
}
}
private void checkBallMovementAndPosition() {
if (w1 < 0 && h1 < 0) {
w1 = this.getWidth() / 2;
h1 = this.getHeight() / 2;
} else {
w1 += w1_V;
h1 += h1_V;
if ((w1 > this.getWidth() - bm_w) || (w1 < 0)) {
w1_V = w1_V * -1;
w1 += w1_V;
}
if ((h1 > this.getHeight() - bm_h) || (h1 < 0)) {
h1_V = h1_V * -1;
h1 += h1_V;
}
}
}
}
}
Note: Replace the images with Your images.

how to set separate toast message for 2 bitmap in android?

public class Sample2 extends Activity {
private SampleView sView;
private static int displayWidth = 100; //movement area
private static int displayHeight = 100;
float angle = 0;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
sView = new SampleView(this);
setContentView(sView);
}//oncreate
private class SampleView extends View {
Context con;
private Rect displayRect = null; //rect we display to
private int scrollRectX = 0; //current left location of scroll rect
private int scrollRectY = 0; //current top location of scroll rect
private float scrollByX = 0; //scroll by amounts
private float scrollByY = 0;
private float startX = 0; //track x from one ACTION_MOVE to the next
private float startY = 0; //track y from one ACTION_MOVE to the next
private int state = 0;
Bitmap bitmap2;
public SampleView(Context context) {
super(context);
displayRect = new Rect(0, 0, displayWidth, displayHeight);
}//constructor
public boolean onTouchEvent(MotionEvent event) {
float x;
float y;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//Initial down event location.
startX = event.getRawX();
startY = event.getRawY()-50;
// Log.e("TOUCHED",startY+" "+(scrollRectY+displayHeight));
if (((startX>scrollRectX)&(startX<(scrollRectX+displayWidth)))&
((startY>scrollRectY)&(startY<(scrollRectY+displayHeight)))) state = 1;
//Log.e("TOUCHED","State "+state);
break;
case MotionEvent.ACTION_MOVE:
x = event.getRawX();
y = event.getRawY()-50;
scrollByX = x - startX;
scrollByY = y - startY;
startX = x;
startY = y;
if (state != 0) invalidate(); //move it
break;
case MotionEvent.ACTION_UP:
x = event.getRawX();
y = event.getRawY()-50;
scrollByX = x - startX;
scrollByY = y - startY;
startX = x;
startY = y;
state = 0;
invalidate();
break;
}//switch
return true;
}//ontouch
protected void onDraw(Canvas canvas) {
scrollRectX = scrollRectX+(int)scrollByX;
scrollRectY = scrollRectY+(int)scrollByY;
displayRect.set(scrollRectX,scrollRectY,scrollRectX+displayWidth,
scrollRectY+displayHeight);
Paint paint = new Paint();
Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
bitmap2= BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher).copy(Config.RGB_565, true);
canvas.drawBitmap(bitmap2, null, displayRect, paint);
//TODO: Fill In Methods Etc.
}
}
}
i have used this code....now my question is this how to set separate toast messages for 2 bitmap in android?....if i touch in background rectangle it shows toast message and if i touch on image it shows another toast message by using if condition on ontouchevents....plz any1 can say this....
you can do like this way,
Demo.java
public class Demo extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_layout);
final LinearLayout lin_layout = (LinearLayout) findViewById(R.id.lin_layout);
final ImageView img_view = (EditText) findViewById(R.id.img_view);
// call your touch event
l_l.setOnClickListener(this);
imageView1.setOnClickListener(this);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.l_l: // if you touch on layout
// do your task
Toast.makeText(getApplicationContext(), "You Touch on: Linear_Layout",
Toast.LENGTH_LONG).show();
break;
case R.id.imageView1: // if you touch on Image
// do your task
Toast.makeText(getApplicationContext(), "You Touch on : Image ", Toast.LENGTH_LONG)
.show();
break;
default:
break;
}
}
}

Image view rotation on ACTION_MOVE

I'm able to rotate image view on ACTION_DOWN.
but its not working for ACTION_MOVE & ACTION_UP.
public class RotateImage extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Rotate rotate;
rotate = new Rotate(this);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(rotate);
}
}
public class Rotate extends ImageView {
Paint paint;
int direction = 0;
private float x;
private float y;
int degree = 0;
float a, b, c;
private float centerX ;
private float centerY ;
private float newX ;
private float newY ;
public Rotate(Context context) {
super(context);
// TODO Auto-generated constructor stub
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStrokeWidth(2);
paint.setStyle(Style.STROKE);
this.setImageResource(R.drawable.direction1);
}
#Override
protected void onDraw(Canvas canvas) {
int height = this.getHeight();
int width = this.getWidth();
centerX = width/2;
centerY = height/2;
canvas.rotate(direction, width / 2, height / 2);
super.onDraw(canvas);
}
public void setDirection(int direction) {
this.direction = direction;
this.invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
System.out.println("now i'm in BEFORE calling MotionEvent.ACTION_MOVE ");
if (event.getAction() == MotionEvent.ACTION_DOWN) {
x = event.getX();
y = event.getY();
newX = centerX-x;
newY = centerY-y;
updateRotation( newX, newY);
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
x = event.getX();
y = event.getY();
newX = centerX-x;
newY = centerY-y;
updateRotation( newX, newY);
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
x = event.getX();
y = event.getY();
newX = centerX-x;
newY = centerY-y;
updateRotation( newX, newY);
}
return super.onTouchEvent(event);
}
private void updateRotation(float newX2, float newY2) {
// TODO Auto-generated method stub
degree = (int)Math.toDegrees(Math.atan2(newY, newX))-90;
setDirection(degree);
}
}
any suggestion would be appropriated
Return true instead of super.onTouchEvent(event) in your onTouchEvent method. This will inform the OS that you are handling the touch event allowing it to provide you with further touch events (e.g. MotionEvent.ACTION_MOVE).

Categories

Resources