Get position of imageview on layout android - android

Please help me i want to get position of imageview on a layout.

x = imageViewObject.getLeft();
y = imageViewObject.getTop();
Hope, it help you!

You can use this with getLocationOnScreen(int [])

At runtime you can get the location of every View object (this includes Layouts too) with
Left Position of View Object getleft()
Top Position of View Object getTop()
Right Position of View Object getRight()
Bottom Position of View Object getBottom()
Even you can get the location with
getLocationOnScreen(int [] )

Position meaning x and y and height and width?
This layout is a view, that view has these properties.

the below code works for me to get the original spot i used the global boolean variable moved to find the value once in the onTouch method v.getX() and ...getY() gets the value of my imageView object I have run this on my apk file on a device and it works perfectly. hope this helps
joystick.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(moved){
moved = false;
xOrigin = v.getX();
yOrigin = v.getY();
mode.setText(Float.toString(xOrigin));
challenge.setText(Float.toString(yOrigin));
}
mode.setText(Float.toString(v.getX()));
challenge.setText(Float.toString(v.getY()));
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
xCoOrdinate = v.getX() - event.getRawX();
yCoOrdinate = v.getY() - event.getRawY();
//mode.setText(Float.toString(v.getX()));
//challenge.setText(Float.toString(v.getY()));
break;
case MotionEvent.ACTION_MOVE:
v.animate().x(event.getRawX() + xCoOrdinate).y(event.getRawY() + yCoOrdinate).setDuration(0).start();
if(v.getX() < xOrigin -50){
v.animate().x(xOrigin -50).setDuration(0).start();
}
else if(v.getX() > xOrigin +50) {
v.animate().x(xOrigin +50).setDuration(0).start();
}
if(v.getY() < yOrigin -50){
v.animate().y(yOrigin -50).setDuration(0).start();
}
else if(v.getY() > yOrigin +50) {
v.animate().y(yOrigin +50).setDuration(0).start();
}
break;
default:
v.setX(xOrigin);
v.setY(yOrigin);
mode.setText(Float.toString(xOrigin));
challenge.setText(Float.toString(yOrigin));
return false;
}
return true;
}
});

Related

How to clear child layout in android?

I am developing an android application where I am creating dynamic Images arrow on relative layout. The images are created on a x,y coordinated of the click area of relative layout. Below is the code the I am using for it.
presciptionScreenArrowImg.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (canSelectMedianStatus == 2) {
if (event == simulationEvent)
return false;
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
Log.e("onTouchListener", "User touch at X:" + x + " Y:" + y);
pointerArrow = new ImageView(getApplication());
pointerArrow.setImageResource(R.drawable.pointer);
pointerArrow.setId(imageArrayTag);
imageArrayTag++;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(40, 40);
params.topMargin = y;
params.leftMargin = x;
pointerArrow.setLayoutParams(params);
presciptionScreenArrowImg.addView(pointerArrow);
long length = 0;
if (action == MotionEvent.ACTION_DOWN) {
// click(v, x, y);
}
}
return false;
}
});
Now, I need is there on button click the last Image drawn should remove first. Basically I need an undo functionality to remove Images as LIFO structure.
let consider presciptionScreenArrowImg is your main layout which contains your all views so for removing
int index=presciptionScreenArrowImg.getChildCount();
if(index>0)
presciptionScreenArrowImg.removeViewAt(index-1);
from above get count of child and remove last view if you have any problem let me know
Store the views in a Queue, and when you add a new view check if the queue is full. If it is, pop a view from the queue, and call presciptionScreenArrowImg.remove(poppedView);

Android view drag drop - accept view drop only if it matches certain view position?

Hello every body I'm working on an android game that allows user to drag some views and place them above another.
I'm kinda newbie and so far i was able to achieve the drag and drop operation, but now the user is allowed to let the view any where in the screen.
All i want to do is to reset the view to its original location if it wasn't placed above any of the views that acts as a drop zone. please help.
This is pretty late! however I successfully accomplished it many days ago and now I have the time to share my solution in case any one is interested... I'll explain how I managed to do it on the following simplified example as my original code is pretty large to attach
as indicated in my illustrative example above there are:
2 Image Views (let1, let2) with two Relative Layouts (let1Container, let2Container)
Additionally there are two blank Image Views (slot1, slot2) that are intended to act as drop zones, along with their containers (slot1Container, slot2Container) of type (Relative Layout)
All placed in RelativeLayout filling the screen and named (dragAreaRelativeLayout)
first we set the ontouchListener for both letter views:
let1_ImageView.setOnTouchListener(this);
let2_ImageView.setOnTouchListener(this);
and then we make our activity implements View.OnTouchListener and provide an implementation of the method like the following :
#Override
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
// detach the child from its parent
parent.removeView(view);
}
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(view.getLayoutParams());
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
layoutParams.leftMargin = X - 25;
layoutParams.topMargin = Y - 25;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
viewRootLayout.addView(view);
break;
case MotionEvent.ACTION_UP:
adjustLocation(view, X, Y);
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
viewRootLayout = (ViewGroup) findViewById(R.id.dragAreaRelativeLayout);
layoutParams.leftMargin = X - 25;
layoutParams.topMargin = Y - 25;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
viewRootLayout.addView(view);
break;
}
viewRootLayout.invalidate();
return true;
}
the previous code allows the user to drag the letters to any where in the screen and calls a method I named as adjustLocation(view, X, Y); once the dragged image is released at MotionEvent.ACTION_UP this method will check if the dragged image is placed in one of the slots and in case it is not correctly placed it will put it back to its original location and here is how it works...
void adjustLocation(View view, int X, int Y) {
RelativeLayout.LayoutParams slot1_LayoutParams = (RelativeLayout.LayoutParams) slot1.getLayoutParams();
RelativeLayout.LayoutParams slot2_LayoutParams = (RelativeLayout.LayoutParams) slot2.getLayoutParams();
int[] slot1_viewLocation = new int[2];
int[] slot2_viewLocation = new int[2];
slot1.getLocationInWindow(slot1_viewLocation);
slot2.getLocationInWindow(slot1_viewLocation);
//detect drop zone boundaries and check if the view is dropped at relative location
if (Y >= slot1_viewLocation[1] && (Y < (slot1_viewLocation[1] + slot1.getHeight()))) {
//first we check if it is placed over SLOT 1
if ((X >= slot1_viewLocation[0]) && (X < (slot1_viewLocation[0] + slot1.getWidth()))) {
view.setLayoutParams(slot1_LayoutParams);
viewRootLayout = (ViewGroup) findViewById(R.id.slot1Container);
viewRootLayout.addView(view);
}
} else if (Y >= slot2_viewLocation[1] && (Y < (slot2_viewLocation[1] + slot2.getHeight()))) {
//then we check if it is placed over SLOT 2
if ((X >= slot2_viewLocation[0]) && (X < (slot2_viewLocation[0] + slot2.getWidth()))) {
view.setLayoutParams(slot2_LayoutParams);
viewRootLayout = (ViewGroup) findViewById(R.id.let2SlotRelativeLayout);
viewRootLayout.addView(view);
}
} else {
// if the dragged image wasn't dropped neither in slot 1 or slot 2 (drop zaone 1,2)
// we send it back to its location
resetViewLocation(view);
}
}
now let us send the miss placed image back to where it came from, to do so I managed to keep track of veiws original LayoutParams at onCreate()
let1_LayoutParams = (RelativeLayout.LayoutParams) let1.getLayoutParams();
let2_LayoutParams = (RelativeLayout.LayoutParams) let2.getLayoutParams();
and finally here is how we reset its location to the original location :
void resetViewLocation(View view) {
ViewGroup viewOriginalLayout = null;
RelativeLayout.LayoutParams viewOriginalParams = null;
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
// detach the child from current parent
parent.removeView(view);
}
int viewId = view.getId();
if (viewId == let1.getId()) {
viewOriginalParams = let1_LayoutParams;
viewOriginalLayout = (ViewGroup) findViewById(R.id.let1Container);
} else if (viewId == let2.getId()) {
viewOriginalParams = let2_LayoutParams;
viewOriginalLayout = (ViewGroup) findViewById(R.id.let2Container);
}
view.setLayoutParams(viewOriginalParams);
viewOriginalLayout.addView(view);
viewOriginalLayout.invalidate();
}
Please be noted that all snippets included are not tested I just wrote them at the moment I was posting this answer. However the technique is working like charm to me and this code is supposed to work as well, I'll just leave you to try and I'll gladly offer any help if needed.
P.S. I don't know if this is really the best way to do it but I'm done waiting and wanted to move on, so any ideas to enhance the code or the technique will be more than appreciated.

Pull to Zoom Animation

Many of us must have come across apps like Tinder and Dripper where you can pull down on the view containing an image and the image zooms in. And then when you let it go, the image zooms out to go back to its origin state.
Let's take an example from Tinder :
Original State: and Zoomed-in state when pulled:
In iOS it is done by
- (void)viewDidLoad {
[super viewDidLoad];
self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"church-welcome.png"]];
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
self.cachedImageViewSize = self.imageView.frame;
[self.tableView addSubview:self.imageView];
[self.tableView sendSubviewToBack:self.imageView];
self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 170)];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat y = -scrollView.contentOffset.y;
if (y > 0) {
self.imageView.frame = CGRectMake(0, scrollView.contentOffset.y, self.cachedImageViewSize.size.width+y, self.cachedImageViewSize.size.height+y);
self.imageView.center = CGPointMake(self.view.center.x, self.imageView.center.y);
}
}
Since my expertise in Objective C and iOS is very limited, I am not being able to implement it in Android.
Here is what I think should be done :
catch the pull-down gesture
increase the height of the view by the pull amount
do some sort of scale animation on the Image to fit it in the expanded view
Does anyone have any idea if there is any library that could be used for this purpose?
Check out this project:
https://github.com/Gnod/ParallaxListView
If you combine it with the ViewPagerIndicator library, you pretty much get Tinder's profile page feature set
https://github.com/JakeWharton/Android-ViewPagerIndicator
I think the easiest way is to override the onTouchEvent method of View.
Something like this:
boolean inZoom = false;
float prevY = 0;
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventY = event.getY();
float eventX = event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(touchedTheImage(eventX, eventY)){
setZoomCenter(eventX, eventY);
prevY = eventY;
inZoom = true;
return true;
}
break;
case MotionEvent.ACTION_MOVE:
if(inZoom){
changeZoomLevel(prevY, eventY);
return true;
}
break;
case MotionEvent.ACTION_UP:
if(inZoom){
resetZoomLevel();
inZoom = false;
return true;
}
break;
}
return false;
}
EDIT:
for the animation part consider this post:
https://stackoverflow.com/a/6650473/3568892

How to config the response time for LongClick?

In Android, View.onLongClickListener() takes about 1 sec to treat it as a long click. How can I configure the response time for a long click?
The default time out is defined by ViewConfiguration.getLongPressTimeout().
You can implement your own long press:
boolean mHasPerformedLongPress;
Runnable mPendingCheckForLongPress;
#Override
public boolean onTouch(final View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if (!mHasPerformedLongPress) {
// This is a tap, so remove the longpress check
if (mPendingCheckForLongPress != null) {
v.removeCallbacks(mPendingCheckForLongPress);
}
// v.performClick();
}
break;
case MotionEvent.ACTION_DOWN:
if( mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new Runnable() {
public void run() {
//do your job
}
};
}
mHasPerformedLongPress = false;
v.postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout());
break;
case MotionEvent.ACTION_MOVE:
final int x = (int) event.getX();
final int y = (int) event.getY();
// Be lenient about moving outside of buttons
int slop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop();
if ((x < 0 - slop) || (x >= v.getWidth() + slop) ||
(y < 0 - slop) || (y >= v.getHeight() + slop)) {
if (mPendingCheckForLongPress != null) {
v. removeCallbacks(mPendingCheckForLongPress);
}
}
break;
default:
return false;
}
return false;
}
This may be late to answer but in case of someone needed.
You can change the time out if your phone is rooted.
simply set the value in database to desired time out value. This will effect system wide long press event.
directory: /data/data/com.android.providers.settings/databases
file : settings.db
table : secure
name : long_press_timeout
By coding ? you may need system app privilege. not so sure actually.
but if you back track the ViewConfiguration.getLongPressTimeout() method, you will see that the constant value is coming from Settings.Secure.LONG_PRESS_TIMEOUT which is a mapping for settings.db
time out set operation is written in View class so it effects every view.

How to implement Drag and drop in ListView to another Listview?

I am implementing Drag and Drop from ListView to another ListView,i got sample app here,
How to Drag drop Listview item to another Listview
using above app created one app,It's working fine up to 4th image of ListView.In my view By default ListView display up to 3rd position(means 0,1,2,3),if i drag the 2nd position from first ListView and drop in second ListView,It's display same image.When i scroll down,positions is 4,5,6,7.if i drag 6th position,it's takes 2nd position. please help me
You should use a for loop .Then give the count of number to the list and check with each count.Check if the id's of the loops are the same if they are different you will directly get different images at the stored place.
public boolean onTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
final int action = ev.getAction();
final int x = (int) ev.getX();
final int y = (int) ev.getY();
if (action == MotionEvent.ACTION_DOWN && x < this.getWidth()/4) {
mDragMode = true;
}
if (!mDragMode)
return super.onTouchEvent(ev);
switch (action) {
case MotionEvent.ACTION_DOWN:
mStartPosition = pointToPosition(x,y);
if (mStartPosition != INVALID_POSITION) {
int mItemPosition = mStartPosition - getFirstVisiblePosition();
mDragPointOffset = y - getChildAt(mItemPosition).getTop();
mDragPointOffset -= ((int)ev.getRawY()) - y;
startDrag(mItemPosition,y);
drag(0,y);// replace 0 with x if desired
}
break;
case MotionEvent.ACTION_MOVE:
drag(0,y);// replace 0 with x if desired
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
default:
mDragMode = false;
mEndPosition = pointToPosition(x,y);
stopDrag(mStartPosition - getFirstVisiblePosition());
if (mDropListener != null && mStartPosition != INVALID_POSITION && mEndPosition != INVALID_POSITION)
mDropListener.onDrop(mStartPosition, mEndPosition);
break;
}
return true;
}
this will help u to push the code in from one location to another.And on the Drag method specify the x&y where you want to push it.

Categories

Resources