How to apply pinch zoom on stickerView/ClipArt/ custom view android - android

How to apply pinch zoom on stickerView or ClipArt or custom view android. I tried this demo.
but not succeeded sometimes it will disappear view some time view become stuck, it worked fine when i want to zoom-in zoom-out from button but not on multi-touch.
screenshot:
Java
public class ClipArt extends RelativeLayout {
int baseh;
int basew;
int basex;
int basey;
ImageButton btndel;
ImageButton btnrot;
ImageButton btnscl;
RelativeLayout clip;
Context cntx;
boolean freeze = false;
int h;
int i;
ImageView image;
String imageUri;
boolean isShadow;
int iv;
RelativeLayout layBg;
RelativeLayout layGroup;
RelativeLayout.LayoutParams layoutParams;
public LayoutInflater mInflater;
int margl;
int margt;
float opacity = 1.0F;
Bitmap originalBitmap;
int pivx;
int pivy;
int pos;
Bitmap shadowBitmap;
float startDegree;
String[] v;
public ClipArt(Context paramContext) {
super(paramContext);
cntx = paramContext;
layGroup = this;
basex = 0;
basey = 0;
pivx = 0;
pivy = 0;
mInflater = ((LayoutInflater) paramContext.getSystemService("layout_inflater"));
mInflater.inflate(R.layout.clipart, this, true);
btndel = ((ImageButton) findViewById(R.id.del));
btnrot = ((ImageButton) findViewById(R.id.rotate));
btnscl = ((ImageButton) findViewById(R.id.sacle));
layoutParams = new RelativeLayout.LayoutParams(250, 250);
layGroup.setLayoutParams(layoutParams);
image = ((ImageView) findViewById(R.id.clipart));
image.setImageResource(R.drawable.ic_launcher);
setOnTouchListener(new View.OnTouchListener() {
final GestureDetector gestureDetector = new GestureDetector(ClipArt.this.cntx,
new GestureDetector.SimpleOnGestureListener() {
public boolean onDoubleTap(MotionEvent paramAnonymous2MotionEvent) {
return false;
}
});
public boolean onTouch(View paramAnonymousView, MotionEvent event) {
if (!ClipArt.this.freeze) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
layGroup.invalidate();
gestureDetector.onTouchEvent(event);
layGroup.performClick();
basex = ((int) (event.getRawX() - layoutParams.leftMargin));
basey = ((int) (event.getRawY() - layoutParams.topMargin));
break;
case MotionEvent.ACTION_MOVE:
int i = (int) event.getRawX();
int j = (int) event.getRawY();
layBg = ((RelativeLayout) getParent());
if ((i - basex > -(layGroup.getWidth() * 2 / 3))
&& (i - basex < layBg.getWidth() - layGroup.getWidth() / 3)) {
layoutParams.leftMargin = (i - basex);
}
if ((j - basey > -(layGroup.getHeight() * 2 / 3))
&& (j - basey < layBg.getHeight() - layGroup.getHeight() / 3)) {
layoutParams.topMargin = (j - basey);
}
layoutParams.rightMargin = -1000;
layoutParams.bottomMargin = -1000;
layGroup.setLayoutParams(layoutParams);
break;
}
return true;
}
return true;
}
});
this.btnscl.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint({ "NewApi" })
public boolean onTouch(View paramAnonymousView, MotionEvent event) {
if (!ClipArt.this.freeze) {
int j = (int) event.getRawX();
int i = (int) event.getRawY();
layoutParams = (RelativeLayout.LayoutParams) layGroup.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
ClipArt.this.layGroup.invalidate();
ClipArt.this.basex = j;
ClipArt.this.basey = i;
ClipArt.this.basew = ClipArt.this.layGroup.getWidth();
ClipArt.this.baseh = ClipArt.this.layGroup.getHeight();
int[] loaction = new int[2];
layGroup.getLocationOnScreen(loaction);
margl = layoutParams.leftMargin;
margt = layoutParams.topMargin;
break;
case MotionEvent.ACTION_MOVE:
float f2 = (float) Math.toDegrees(Math.atan2(i - ClipArt.this.basey, j - ClipArt.this.basex));
float f1 = f2;
if (f2 < 0.0F) {
f1 = f2 + 360.0F;
}
j -= ClipArt.this.basex;
int k = i - ClipArt.this.basey;
i = (int) (Math.sqrt(j * j + k * k)
* Math.cos(Math.toRadians(f1 - ClipArt.this.layGroup.getRotation())));
j = (int) (Math.sqrt(i * i + k * k)
* Math.sin(Math.toRadians(f1 - ClipArt.this.layGroup.getRotation())));
k = i * 2 + ClipArt.this.basew;
int m = j * 2 + ClipArt.this.baseh;
if (k > 150) {
layoutParams.width = k;
layoutParams.leftMargin = (ClipArt.this.margl - i);
}
if (m > 150) {
layoutParams.height = m;
layoutParams.topMargin = (ClipArt.this.margt - j);
}
ClipArt.this.layGroup.setLayoutParams(layoutParams);
ClipArt.this.layGroup.performLongClick();
break;
}
return true;
}
return ClipArt.this.freeze;
}
});
this.btnrot.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint({ "NewApi" })
public boolean onTouch(View paramAnonymousView, MotionEvent event) {
if (!ClipArt.this.freeze) {
layoutParams = (RelativeLayout.LayoutParams) ClipArt.this.layGroup.getLayoutParams();
ClipArt.this.layBg = ((RelativeLayout) ClipArt.this.getParent());
int[] arrayOfInt = new int[2];
layBg.getLocationOnScreen(arrayOfInt);
int i = (int) event.getRawX() - arrayOfInt[0];
int j = (int) event.getRawY() - arrayOfInt[1];
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
ClipArt.this.layGroup.invalidate();
ClipArt.this.startDegree = layGroup.getRotation();
ClipArt.this.pivx = (layoutParams.leftMargin + ClipArt.this.getWidth() / 2);
ClipArt.this.pivy = (layoutParams.topMargin + ClipArt.this.getHeight() / 2);
ClipArt.this.basex = (i - ClipArt.this.pivx);
ClipArt.this.basey = (ClipArt.this.pivy - j);
break;
case MotionEvent.ACTION_MOVE:
int k = ClipArt.this.pivx;
int m = ClipArt.this.pivy;
j = (int) (Math.toDegrees(Math.atan2(ClipArt.this.basey, ClipArt.this.basex))
- Math.toDegrees(Math.atan2(m - j, i - k)));
i = j;
if (j < 0) {
i = j + 360;
}
ClipArt.this.layGroup.setRotation((ClipArt.this.startDegree + i) % 360.0F);
break;
}
return true;
}
return ClipArt.this.freeze;
}
});
this.btndel.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
if (!ClipArt.this.freeze) {
layBg = ((RelativeLayout) ClipArt.this.getParent());
layBg.performClick();
layBg.removeView(ClipArt.this.layGroup);
}
}
});
}
public void disableAll() {
this.btndel.setVisibility(4);
this.btnrot.setVisibility(4);
this.btnscl.setVisibility(4);
}
public ImageView getImageView() {
return this.image;
}
public void setFreeze(boolean paramBoolean) {
this.freeze = paramBoolean;
}
}
Layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
<ImageButton android:id="#+id/rotate" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:adjustViewBounds="true" android:background="#android:color/transparent" android:scaleType="fitCenter" android:src="#drawable/rotation"/>
<ImageButton android:id="#+id/sacle" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:adjustViewBounds="true" android:background="#android:color/transparent" android:scaleType="fitCenter" android:src="#drawable/pointer"/>
<ImageButton android:id="#+id/del" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:adjustViewBounds="true" android:background="#android:color/transparent" android:scaleType="fitCenter" android:src="#drawable/close"/>
<ImageView android:id="#+id/clipart" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp"/>
</RelativeLayout>

Related

Auto moving TextView across the screen

I am trying to make TextView which moves across the screen in all directions randomly using translateAnimation. I need text moving like in screen saver for example going round and round until it is clicked.But have some problems:
1. text moves just from top to bottom
2.it doesn't stop in screen borders , it is going off the screen then coming back again :
public class aktivityStarted extends AppCompatActivity {
TextView textMovin;
/* int loc[]=new int[2];
int x=loc[0];
int y=loc[1];*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aktivity_started);
textMovin=findViewById(R.id.movingText);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
final int width = displaymetrics.widthPixels-textMovin.getWidth();
final int height = displaymetrics.heightPixels-textMovin.getHeight();
final Random r = new Random();
final int translationX = r.nextInt(width);
final int translationY = r.nextInt(height);
final int randomx=r.nextInt(50)+1;
final int randomy=r.nextInt(50)+1;
final TranslateAnimation anim = new TranslateAnimation(-translationX,translationX ,-translationY,translationY ); //Use current view position instead of `currentX` and `currentY`
anim.setDuration(2500);
anim.setRepeatCount(-1);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
anim.reset();
anim.setRepeatMode(Animation.REVERSE);
anim.setFillAfter(true);
}
#Override
public void onAnimationRepeat(Animation animation) {
textMovin.setY(r.nextInt(height));
textMovin.setX(r.nextInt(width));
anim.start();
}
});
textMovin.startAnimation(anim);
}
}
try this code:
public class MainActivity extends AppCompatActivity {
private View parent;
private TextView textMovin;
private float speedX;
private float speedY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textMovin = findViewById(R.id.textV);
parent = findViewById(R.id.parent);
final Random r = new Random();
speedX = r.nextFloat() * 200;
speedY = r.nextFloat() * 200;
parent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
final int width = parent.getWidth() - textMovin.getWidth();
final int height = parent.getHeight() - textMovin.getHeight();
final int period = 50;
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
textMovin.post(new TimerTask() {
#Override
public void run() {
textMovin.setX(speedX * period / 1000.0f + textMovin.getX());
textMovin.setY(speedY * period / 1000.0f + textMovin.getY());
if (textMovin.getY() <= 0 || textMovin.getY() >= height)
speedY *= -1;
if (textMovin.getX() <= 0 || textMovin.getX() >= width)
speedX *= -1;
}
});
}
}, 50, period);
}
});
findViewById(R.id.random).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Random r = new Random();
speedX = r.nextFloat() * 200;
speedY = r.nextFloat() * 200;
}
});
}
}
and the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello World!" />
<Button
android:id="#+id/random"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:text="Random" />
</RelativeLayout>
Hope it works for you.
public class OnDragTouchListener implements View.OnTouchListener {
/**
* Callback used to indicate when the drag is finished
*/
public interface OnDragActionListener {
/**
* Called when drag event is started
*
* #param view The view dragged
*/
void onDragStart(View view);
/**
* Called when drag event is completed
*
* #param view The view dragged
*/
void onDragEnd(View view);
}
private View mView;
private View mParent;
private boolean isDragging;
private boolean isInitialized = false;
private int width;
private float xWhenAttached;
private float maxLeft;
private float maxRight;
private float dX;
private int height;
private float yWhenAttached;
private float maxTop;
private float maxBottom;
private float dY;
private OnDragActionListener mOnDragActionListener;
public OnDragTouchListener(View view) {
this(view, (View) view.getParent(), null);
}
public OnDragTouchListener(View view, View parent) {
this(view, parent, null);
}
public OnDragTouchListener(View view, OnDragActionListener onDragActionListener) {
this(view, (View) view.getParent(), onDragActionListener);
}
public OnDragTouchListener(View view, View parent, OnDragActionListener onDragActionListener) {
initListener(view, parent);
setOnDragActionListener(onDragActionListener);
}
public void setOnDragActionListener(OnDragActionListener onDragActionListener) {
mOnDragActionListener = onDragActionListener;
}
public void initListener(View view, View parent) {
mView = view;
mParent = parent;
isDragging = false;
isInitialized = false;
}
public void updateBounds() {
updateViewBounds();
updateParentBounds();
isInitialized = true;
}
public void updateViewBounds() {
width = mView.getWidth();
xWhenAttached = mView.getX();
dX = 0;
height = mView.getHeight();
yWhenAttached = mView.getY();
dY = 0;
}
public void updateParentBounds() {
maxLeft = 0;
maxRight = maxLeft + mParent.getWidth();
maxTop = 0;
maxBottom = maxTop + mParent.getHeight();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isDragging) {
float[] bounds = new float[4];
// LEFT
bounds[0] = event.getRawX() + dX;
if (bounds[0] < maxLeft) {
bounds[0] = maxLeft;
}
// RIGHT
bounds[2] = bounds[0] + width;
if (bounds[2] > maxRight) {
bounds[2] = maxRight;
bounds[0] = bounds[2] - width;
}
// TOP
bounds[1] = event.getRawY() + dY;
if (bounds[1] < maxTop) {
bounds[1] = maxTop;
}
// BOTTOM
bounds[3] = bounds[1] + height;
if (bounds[3] > maxBottom) {
bounds[3] = maxBottom;
bounds[1] = bounds[3] - height;
}
switch (event.getAction()) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
onDragFinish();
break;
case MotionEvent.ACTION_MOVE:
mView.animate().x(bounds[0]).y(bounds[1]).setDuration(0).start();
break;
}
return true;
} else {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isDragging = true;
if (!isInitialized) {
updateBounds();
}
dX = v.getX() - event.getRawX();
dY = v.getY() - event.getRawY();
if (mOnDragActionListener != null) {
mOnDragActionListener.onDragStart(mView);
}
return true;
}
}
return false;
}
private void onDragFinish() {
if (mOnDragActionListener != null) {
mOnDragActionListener.onDragEnd(mView);
}
dX = 0;
dY = 0;
isDragging = false;
}
}
And you can set it using:
myView.setOnTouchListener(new OnDragTouchListener(myView));
Or by adding this directly in init method of your Custom View:
setOnTouchListener(new OnDragTouchListener(this));

Xamarin Imageview Drag Sample

(Xamarin with Visual Studio 2015 ) I want to implement a simple Activity inwith an Imageview, which can be moved/dragged with touch: This is what I have implemented, but the Image is flickering and moving slower. Can you give me an example how to implement this?
Thanks for your help!
private void TouchMeImageViewOnTouch(object sender, View.TouchEventArgs touchEventArgs)
{
View bild = (View)sender;
RelativeLayout.LayoutParams layouti = (RelativeLayout.LayoutParams)bild.LayoutParameters;
switch (touchEventArgs.Event.Action & MotionEventActions.Mask)
{
case MotionEventActions.Down:
xDelta = touchEventArgs.Event.GetX()-layouti.LeftMargin;
yDelta = touchEventArgs.Event.GetX() - layouti.LeftMargin;
break;
case MotionEventActions.Move:
int wert = (int)touchEventArgs.Event.GetX();
yvalue = touchEventArgs.Event.GetY()-yDelta;
xvalue = touchEventArgs.Event.GetX()-xDelta;
float xdpi = (int) Resources.DisplayMetrics.Density;
layouti.LeftMargin = (int)xvalue;
layouti.TopMargin = (int)yvalue;
container.Invalidate();
break;
case MotionEventActions.Up:
break;
default:
break;
}
xPositionText.Text = xvalue.ToString();
yPositionText.Text = yvalue.ToString();
}
I have tried to implement a dragable imageview for testing. the drag is slow in the android emulator. But by testing it in the real device it works fine and move fast.
Try the following code sampleļ¼š
public class MainActivity : Activity, IOnTouchListener
{
Button dragAbleBt;
ImageView imgV1;
int screenWidth = 0;
int screenHeight = 0;
int lastX = 0, lastY = 0;
public bool OnTouch(View v, MotionEvent e)
{
MotionEventActions ea = e.Action;
switch (ea) {
case MotionEventActions.Down:
lastX = (int)e.RawX;
lastY = (int)e.RawY;
break;
case MotionEventActions.Move:
int dx = (int)e.RawX - lastX;
int dy = (int)e.RawY - lastY;
int left = v.Left + dx;
int right = v.Right + dx;
int top = v.Top + dy;
int bottom = v.Bottom + dy;
if (left < 0)
{
left = 0;
right = left + v.Width;
}
if (right > screenWidth)
{
right = screenWidth;
left = right - v.Width;
}
if (top < 0)
{
top = 0;
bottom = top + v.Height;
}
if (bottom > screenHeight)
{
bottom = screenHeight;
top = bottom - v.Height;
}
v.Layout(left, top, right, bottom);
lastX = (int) e.RawX;
lastY = (int) e.RawY;
v.PostInvalidate();
break;
case MotionEventActions.Up:
break;
}
if (v.Id == Resource.Id.imageView1)
{
return true;
}
return false;
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView (Resource.Layout.Main);
//DisplayMetrics dm = Resources.DisplayMetrics;
//screenWidth = dm.WidthPixels;
//screenHeight = dm.HeightPixels;
dragAbleBt = FindViewById<Button>(Resource.Id.button1);
imgV1 = FindViewById<ImageView>(Resource.Id.imageView1);
dragAbleBt.SetOnTouchListener(this);
imgV1.SetOnTouchListener(this);
}
public override void OnWindowFocusChanged(bool hasFocus)
{
base.OnWindowFocusChanged(hasFocus);
if (hasFocus)
{
Rect outRect = new Rect();
this.Window.FindViewById(Window.IdAndroidContent).GetDrawingRect(outRect);
screenWidth = outRect.Width();
screenHeight = outRect.Height();
}
}
}
Please refer the source code to the github

Draggable Button getting out of RelativeLayout whenever dragged

I am developing an application in which I am using Drag and Drop functionality.
In that I am generating buttons OnClick.The code is working fine but when I drag the button to the corners of the relativelayout,button gets out of the layout. I want it to stay inside of the layout.
Before Dragging the button
After Dragging the button (on top corner in this example)
As you can see that the button is getting out of the layout whenever I drag it towards the end/corner of the layout, I want it to stay in the layout intact, display full button. How can I do that?
Thanks in advance.!
MainActivity.java
public class MainActivity extends Activity implements OnTouchListener {
Button btnAddButton;
RelativeLayout rl1;
int i = 1;
private int _xDelta;
private int _yDelta;
ViewGroup _root;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddButton = (Button) findViewById(R.id.btnAdd);
rl1 = (RelativeLayout) findViewById(R.id.relative_layout);
_root = (ViewGroup)findViewById(R.id.relative_layout);
btnAddButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
add(v);
}
});
}
public void add(View v) {
Button btn = new Button(MainActivity.this);
//btn.setId(i);
RelativeLayout.LayoutParams layoutParam = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
int a=(int) (Math.random()*100);
// Toast.makeText(MainActivity.this, String.valueOf(Math.random()*100), 1).show();//double a=Math.random();
layoutParam.leftMargin = 30+a;
if (i > 1) {
layoutParam.addRule(RelativeLayout.BELOW, (i - 1));
}
btn.setText("Button" + i);
rl1.addView(btn, layoutParam);
btn.setOnTouchListener(this);
i++;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
v.setLayoutParams(layoutParams);
break;
}
_root.invalidate();
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="AddButton"
android:text="Button" />
<RelativeLayout
android:id="#+id/relative_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/btnAdd" >
</RelativeLayout>
</RelativeLayout>
I was able to tackle this by using these conditions:
if ((v.getY() < lay.getY())) {
v.setX(xVal);
v.setY(yVal);
} else if (v.getX() < lay.getX()) {
v.setX(xVal);
v.setY(yVal);
} else if (v.getX() + v.getWidth() > lay.getX() + lay.getWidth()) {
v.setX(xVal);
v.setY(yVal);
} else if (v.getY() + v.getHeight() > lay.getY() + lay.getHeight()) {
v.setX(xVal);
v.setY(yVal);
} else {
for (int i = 0; i <= viewIdList.size() - 1; i++) {
if (v.getId() != viewIdList.get(i).getId()) {
View v3 = viewIdList.get(i);
Rect rect1 = new Rect(v.getLeft(), v.getTop(),
v.getRight(), v.getBottom());
v.getHitRect(rect1);
Rect rect2 = new Rect(v3.getLeft(), v3.getTop(),
v3.getRight(), v3.getBottom());
v3.getHitRect(rect2);
if (Rect.intersects(rect1, rect2)) {
System.out.println("overlap");
v.setX(xVal);
v.setY(yVal);
}
where v is the view (ImageView in my case) and this code is written in MotionEvent.ACTION_UP of onTouchListener.

What type of event listener should i use in android?

I have a 5x5 grid (I ve drawn a matrix in canvas). I ve arranged the textviews in the the grid
in the order of a array..ie (5X5 ) array. The thing is I want to change the values on of the text view when I swipe horizontally or vertically.
Say suppose I am using a touch movement on the screen continuously from [4][0] to [4][2] I want to modify the values of the textviews in those places.
Any ideas?
This piece of code might help you:
public class MyClass extends Activity implements OnGestureListener{
ArrayList<TextView> tvs = new ArrayList<TextView>();
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.mygrid);
}
public void onResume() {
super.onResume();
GestureOverlayView gd = (GestureOverlayView)findViewById(R.id.gd);
LinearLayout g = (LinearLayout)findViewById(R.id.mygrid);
gd.addOnGestureListener(this);
g.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < 5; i++) {
LinearLayout row = new LinearLayout(this);
g.addView(row);
row.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams rowlp = (LayoutParams) row.getLayoutParams();
rowlp.width = LayoutParams.MATCH_PARENT;
rowlp.weight = 1;
rowlp.height = LayoutParams.WRAP_CONTENT;
row.setLayoutParams(rowlp);
for (int j = 0; j < 5; j++) {
TextView tv = new TextView(this);
row.addView(tv);
LinearLayout.LayoutParams lp = (LayoutParams) tv.getLayoutParams();
lp.height = LayoutParams.MATCH_PARENT;
lp.width = 0;
lp.weight = 1;
tv.setLayoutParams(lp);
tv.setText(String.valueOf(i * 5 + j));
tv.setTag(String.valueOf(i * 5 + j));
tv.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
tvs.add(tv);
if ((i * 5 + j) % 2 == 0)
tv.setBackgroundColor(0xff888888);
}
}
}
private boolean isPointInsideView(float x, float y, View view){
int location[] = new int[2];
view.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
//point is inside view bounds
if(( x > viewX && x < (viewX + view.getWidth())) &&
( y > viewY && y < (viewY + view.getHeight()))){
return true;
} else {
return false;
}
}
#Override
public void onGesture(GestureOverlayView overlay, MotionEvent event) {
float x = event.getRawX();
float y = event.getRawY();
for (TextView v : tvs) {
if (isPointInsideView(x, y, v)) {
v.setText("HERE");
}
}
}
#Override
public void onGestureCancelled(GestureOverlayView overlay, MotionEvent event) {
}
#Override
public void onGestureEnded(GestureOverlayView overlay, MotionEvent event) {
}
#Override
public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.gesture.GestureOverlayView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gd"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/mygrid"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.gesture.GestureOverlayView>
Hope it helps.
Edit2: replace the methods above with these for highly increased performance:
private TextView getAbove(float x, float y) {
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
if (isPointInsideView(x, y, tvs[i][j]))
return tvs[i][j];
return null;
}
#Override
public void onGesture(GestureOverlayView overlay, MotionEvent event) {
float x = event.getRawX();
float y = event.getRawY();
if (last == null || !isPointInsideView(x, y, last)) {
last = getAbove(x,y);
draw();
}
}
private void draw() {
if (last == null)
return;
last.setText("+");
}
private void reset() {
last = null;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
tvs[i][j].setText(String.valueOf(i * 5 + j));
}
#Override
public void onGestureCancelled(GestureOverlayView overlay, MotionEvent event) {
reset();
}
#Override
public void onGestureEnded(GestureOverlayView overlay, MotionEvent event) {
reset();
}
#Override
public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {
last = getAbove(event.getRawX(), event.getRawY());
draw();
}
TextView[][] tvs = new TextView[5][5];
TextView last = null;
And make the arraylist into an TextView[5][5]

Why moving of GroupView works bad?

I made two nested RelativeLayouts, filled one with some TextViews and made reaction on finger drag guesture.
But it works badly:
1) moving group leaves garbage traces as if background does not redraw
2) the column with leftMargin==800 does not draw
The XML layout code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/stator"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:id="#+id/mover"
android:background="#android:color/darker_gray"
>
</RelativeLayout>
</RelativeLayout>
The java code:
public class SymbolPadActivity extends Activity {
private RelativeLayout mover;
private RelativeLayout stator;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mover = (RelativeLayout) findViewById(R.id.mover);
RelativeLayout.LayoutParams labelParams;
TextView textView;
for(int leftMargin = 0; leftMargin<1500; leftMargin += 200) {
for(int topMargin=0; topMargin<800; topMargin += 80) {
// I can't omit these 3 lines
labelParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
labelParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
labelParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
labelParams.leftMargin = leftMargin;
labelParams.topMargin = topMargin;
textView = new TextView(this);
textView.setText("(" + leftMargin + "," + topMargin + ")");
mover.addView(textView, labelParams);
}
}
stator = (RelativeLayout) findViewById(R.id.stator);
stator.setOnTouchListener(new View.OnTouchListener() {
private int startleft, starttop;
private float startx, starty;
private boolean started;
#Override
public boolean onTouch(View v, MotionEvent event) {
if( event.getActionMasked() == MotionEvent.ACTION_DOWN ) {
started = true;
startx = event.getX();
starty = event.getY();
startleft = mover.getLeft();
starttop = mover.getTop();
return true;
}
else if( event.getActionMasked() == MotionEvent.ACTION_UP ) {
started = false;
startx = starty = 0;
return true;
}
else if( event.getActionMasked() == MotionEvent.ACTION_MOVE ) {
mover.setLeft( startleft + (int)(event.getX() - startx) );
mover.setTop( starttop + (int)(event.getY() - starty) );
return true;
}
else {
return false;
}
}
});
}
}
How to implement my goal correctly (in brief)?

Categories

Resources