Android setX() and setY() behaving weird - android

I am trying to dynamically create and then move an image in an Android activity. However, the setX() and setY() methods seem to not work correctly. It correctly sets the position of an image when it is first created and placed, but any attempt to update it results in the image being placed in the wrong spot. For instance, the image moves on the following code:
ImageView image;
RelativeLayout layout = (RelativeLayout)findViewById(R.id.activity_this);
if(action == MotionEvent.ACTION_DOWN){
image = new ImageView(MyClass.this);
layout.addView(image, width, height);
image.setX(206);
image.setY(206);
}
else if(action == MotionEvent.ACTION_MOVE){
if(image != null){
image.setX(206);
image.setY(206);
}
}
On ACTION_MOVE the image is moved even though the x and y position values remain the same. The parent of the image remains the same. The size remains the same. If I get the x and y values it will still say 206, but it is not placed at (206, 206) on the activity anymore. I am lost as to why this is happening. I can't find any indication that the image has been altered except for it physically changing location.

Really, this shouldn't be happening. Alternatively, try setting another variable and setting x and y to it, or get x and get y and add a 0 to each one of them for same location.
As stated in Android - Use of view.setX() and setY in api 8, if you have searched, there is another solution that also works even before api 8.
LayoutParams works like this -
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //WRAP_CONTENT param can be FILL_PARENT
params.leftMargin = 206; //XCOORD
params.topMargin = 206; //YCOORD
childView.setLayoutParams(params);
There is more information there. I hope this helps

Run into the same issue. View.setLeft(int)/View.setTop(int) worked for me.
Note that since the original post of this answer things changed and on the more recent android versions it may produce unexpected results while it did the trick for me on older versions. So if you are targeting older devices (android 3.0 and below) this may help but for a more generic solution please consider other answers here as well.

From the docs, setTranslationX is:
Sets the horizontal location of this view relative to its left position. This effectively positions the object post-layout, in addition to wherever the object's layout placed it.
And setX is:
Sets the visual x position of this view, in pixels. This is equivalent to setting the translationX property to be the difference between the x value passed in and the current left property.
Thus you can think of setTranlsationX as a relative offset: move 3 pixels left of where you normally would be. And setX is a fixed position: move whatever you have to so that you end up drawing at coordinate X.

Is your activity in full screen mode? If no try to make it to full screen and it should solve your problem.

Pretty late to answer, but if someone else is facing the same problem. This fixed it for me it was the paddings in the layout file:
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"

As someone who actually facing this problem, I have solve this issue by removing any padding in the parentView. The padding seem cause a change in the layout size

Related

Unable to scroll in android with appium using python

I tried this piece of code:
scrollObject = dict(direction="down", text="some_text", element=appium_driver_elem.id)
self.driver.execute_script("mobile: scrollTo", scrollObject)
But I am getting an error saying:
"appium_driver_elem does not have attribute like id" or sometimes nosuchelementexception.
What is the simplest way to scroll with appium in android using python? Any full test examples?
self.driver.swipe(470, 1400, 470, x, 400)
self.driver.swipe(start_x, start_y, end_x, end_y, duration)
start_y value represents bottom Y value & end_y value represents top Y value of the screen in your app.
Since to scroll we hold screen at bottom & move up.
value of x depends on how much you wish to scroll in one shot.
Example: To scroll to the bottom, try 300. To scroll little x can be 1200
Still haven't found an answer. So maybe you need to play a little bit rough.
You can use the self.driver.scroll(self,SrcElem,DestElem) function to swipe screen from bottom to top and check the element you seek.
Or You can also try to do
from appium.webdriver.common.touch_action import TouchAction
...
action = TouchAction(self.driver)
action.press(start_element).move_to(end_element).release().perform()
Actually, that's how scroll() function works. Once, I had an issue with self.driver.scroll(), so this can also be a workaround.

Redrawing clipped content in Android View after moving into bounds

Within Android, I'm trying to move a TextView from outside the parents bounds into view, but the contents never shows up, or remains clipped if it was partially within the bounds already.
Initial situation at start
Situation after animation
(Below this is another view, that was completely out of bounds and isn't drawn either)
I have 4 TextViews below each other in a custom Object extending RelativeLayout. Based on a percentage the top 2 should move outside it's bounds and the bottom 2 should move in (from the bottom).
I use the following code to update the properties of each TextView. In this class each variable **positionY* is filled with their initial position from the layout-xml. effect is percentage between 0 & 1. The animation works, but the views aren't drawn again.
public class ActionBarTitleView extends RelativeLayout {
public void updateTransition(float effect) {
float height = getHeight();
titleView1.setY(title1positionY - height*effect);
detailView1.setY(detail1positionY - height*effect);
titleView2.setY(title2positionY - height*effect);
detailView2.setY(detail2positionY - height*effect);
invalidate();
}
}
What I tried
After some researching I found a few hints what the issue might be, but so far none of the tried options had any effect. Below is a list of things I've found on SO and tried.
Calling invalidate() on the RelativeLayout - No effect.
Invalditing the TextViews - No effect.
clipChildren = false for the RelativeLayout - No effect.
setWillNotDraw = false for the RelativeLayout - No effect. (onDraw is being called)
I haven't tried to solve this with a ScrollView, but I don't want to really, cause that adds another layer in the hierachy for something pretty small.
I thought I understood the drawing logic, but perhaps I'm missing something, so I hope someone might be able to point me in the right direction.
What I ended up doing (September 3rd)
Since no real solution was offered, I tried again and came to the following "fix". I set both second labels to Visibility.GONE, but within the original bounds of the container view. Then when I start the animation, I set their correct values, then move them outside the bounds and finally setting Visiblity.VISIBLE. When the animation progresses the labels roll into view as supposed to. So a fix to the issue, but no real explanation why the TextViews aren't drawn again...

How can I dynamically set the position of view in Android?

How can I change the position of view through code? Like changing its X, Y position. Is it possible?
For anything below Honeycomb (API Level 11) you'll have to use setLayoutParams(...).
If you can limit your support to Honeycomb and up you can use the setX(...), setY(...), setLeft(...), setTop(...), etc.
Yes, you can dynamically set the position of the view in Android. Likewise, you have an ImageView in LinearLayout of your XML file. So you can set its position through LayoutParams.But make sure to take LayoutParams according to the layout taken in your XML file. There are different LayoutParams according to the layout taken.
Here is the code to set:
LayoutParams layoutParams=new LayoutParams(int width, int height);
layoutParams.setMargins(int left, int top, int right, int bottom);
imageView.setLayoutParams(layoutParams);
There are different valid answers already, but none seems to properly suggest which method(s) to use in which case, except for the corresponding API level restrictions:
If you can wait for a layout cycle and the parent view group supports MarginLayoutParams (or a subclass), set marginLeft / marginTop accordingly.
If you need to change the position immediately and persistently (e.g. for a PopupMenu anchor), additionally call layout(l, t, r, b) with the same coordinates. This preempts what the layout system will confirm later.
For immediate (temporary) changes (such as animations), use setX() / setY() instead. In cases where the parent size doesn't depend on WRAP_CHILDREN, it might be fine to use setX() / setY() exclusively.
Never use setLeft() / setRight() / setBottom() / setTop(), see below.
Background:
The mLeft / mTop / mBottom / mRight fields get filled from the corresponding LayoutParams in layout(). Layout is called implicitly and asynchronously by the Android view layout system. Thus, setting the MarginLayoutParams seems to be the safest and cleanest way to set the position permanently. However, the asynchronous layout lag might be a problem in some cases, e.g. when using a View to render a cursor, and it's supposed to be re-positioned and serve as a PopupMenu anchor at the same time. In this case, calling layout() worked fine for me.
The problems with setLeft() and setTop() are:
Calling them alone is not sufficient -- you also need to call setRight() and setBottom() to avoid stretching or shrinking the view.
The implementation of these methods looks relatively complex (= doing some work to account for the view size changes caused by each of them)
They seem to cause strange issues with input fields: EditText soft numeric keyboard sometimes does not allow digits
setX() and setY() work outside of the layout system, and the corresponding values are treated as an additional offset to the left / top / bottom / right values determined by the layout system, shifting the view accordingly. They seem to have been added for animations (where an immediate effect without going through a layout cycle is required).
There is a library called NineOldAndroids, which allows you to use the Honeycomb animation library all the way down to version one.
This means you can define left, right, translationX/Y with a slightly different interface.
Here is how it works:
ViewHelper.setTranslationX(view, 50f);
You just use the static methods from the ViewHelper class, pass the view and which ever value you want to set it to.
I would recommend using setTranslationX and setTranslationY. I'm only just getting started on this myself, but these seem to be the safest and preferred way of moving a view. I guess it depends a lot on what exactly you're trying to do, but this is working well for me for 2D animation.
You can try to use the following methods, if you're using HoneyComb Sdk(API Level 11).
view.setX(float x);
Parameter x is the visual x position of this view.
view.setY(float y);
Parameter y is the visual y position of this view.
I hope it will be helpful to you. :)
For support to all API levels you can use it like this:
ViewPropertyAnimator.animate(view).translationYBy(-yourY).translationXBy(-yourX).setDuration(0);
Set the left position of this view relative to its parent:
view.setLeft(int leftPosition);
Set the right position of this view relative to its parent:
view.setRight(int rightPosition);
Set the top position of this view relative to its parent:
view.setTop(int topPosition);
Set the bottom position of this view relative to its parent:
view.setBottom(int bottomPositon);
The above methods are used to set the position the view related to its parent.
Use LayoutParams.
If you are using a LinearLayout you have to import android.widget.LinearLayout.LayoutParams, else import the proper version of LayoutParams for the layout you're using, or it will cause a ClassCastException, then:
LayoutParams layoutParams = new LayoutParams(int width, int height);
layoutParams.setMargins(int left, int top, int right, int bottom);
imageView.setLayoutParams(layoutParams);
NB: Note that you can use also imageView.setLeft(int dim), BUT THIS WON'T set the position of the component, it will set only the position of the left border of the component, the rest will remain at the same position.
Use RelativeLayout, place your view in it, get RelativeLayout.LayoutParams object from your view and set margins as you need. Then call requestLayout() on your view. This is the only way I know.
In Kotlin you can do it as below;
view
.animate()
.x(50f)
.y(100f)
.duration = 500L
I found that #Stefan Haustein comes very close to my experience, but not sure 100%. My suggestion is:
setLeft() / setRight() / setBottom() / setTop() won't work sometimes.
If you want to set a position temporarily (e.g for doing animation, not affected a hierachy) when the view was added and shown, just use setX()/ setY() instead. (You might want search more in difference setLeft() and setX())
And note that X, Y seem to be absolute, and it was supported by AbsoluteLayout which now is deprecated. Thus, you feel X, Y is likely not supported any more. And yes, it is, but only partly. It means if your view is added, setX(), setY() will work perfectly; otherwise, when you try to add a view into view group layout (e.g FrameLayout, LinearLayout, RelativeLayout), you must set its LayoutParams with marginLeft, marginTop instead (setX(), setY() in this case won't work sometimes).
Set position of the view by marginLeft and marginTop is an unsynchronized process. So it needs a bit time to update hierarchy. If you use the view straight away after set margin for it, you might get a wrong value.
One thing to keep in mind with positioning is that each view has an index relative to its parent view. So if you have a linear layout with three subviews, the subviews will each have an index: 0, 1, 2 in the above case.
This allows you to add a view to the last position (or the end) in a parent view by doing something like this:
int childCount = parent.getChildCount();
parentView.addView(newView, childCount);
Alternatively you could replace a view using something like the following:
int childIndex = parentView.indexOfChild(childView);
childView.setVisibility(View.GONE);
parentView.addView(newView, childIndex);

Android - How to draw a letter at a specific point?

I want to fill the screen with a 100 different letters in random positions. On the iPhone I just created a bunch of UILabels set their x and y positions and then used animations to move them about.
On Android it doesn't look like I can add a TextView to my view and specify its X and Y. Is there a way to do this?
View gameView = findViewById(R.id.gameboard);
tv = new TextView(gameView.getContext());
tv.setText("A");
tv.setWidth(w); tv.setHeight(h);
// How to set the X and Y?
EDIT: The solution was to use AbsoluteLayout:
AbsoluteLayout al = (AbsoluteLayout)findViewById(R.id.gb_layout);
tv = new TextView(this);
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(
AbsoluteLayout.LayoutParams.WRAP_CONTENT,
AbsoluteLayout.LayoutParams.WRAP_CONTENT,10,10);
params.x = 50;
params.y = 50;
al.addView(tv, params);
and to move it base on MotionEvent me:
AbsoluteLayout.LayoutParams p = new AbsoluteLayout.LayoutParams(
AbsoluteLayout.LayoutParams.WRAP_CONTENT,
AbsoluteLayout.LayoutParams.WRAP_CONTENT,(int)me.getX(), (int)me.getY());
mTV.setLayoutParams (p);
I think you are making a game and for this you should look into SurfaceView here is an good example then
1...if you look into code there is onDraw method where you will get the width of screen and height
2...Now taking this width and height as seed for random generator get x and y position.
3...Iterate through point 2 100 times and you will get the desired result
You can use a FrameLayout for this. Set each TextView's background to transparent and add it to the FrameLayout. Make each TextView, and the FrameLayout, fill their parent. The FrameLayout places all its child views at (0,0). To move letters around, just change the top and left padding of the corresponding TextView.
In android positioning child views is the responsibility of the layout class.
You need to create a custom.layout and overide the onLayout method. In this method you can iterate through all the child views calling View.layout(left,top,right,bottom) on each child.
i found this example code whilst trawling the net :
https://gist.github.com/882650
You should also check out view.setTranslationX (and Y) which might be exactly what you need
I'm not entirely sure how you'd go about doing this in code, but you need to use an absolute layout as your root element. (edit: Do not use absolute layout, as it was pointed out that it is deprecated. The closest alternative seems to be RelativeLayout.)
The properties in the XML format for the absolute layout coordinates are layout_x and layout_y.
edit: A little research is saying you need to be using setLayoutParams, but my Eclipse IDE is not working properly, so unfortunately I can't test exactly what you're looking for.

Programmatically resize of view depends on android version?

I am facing a weird behavior regarding the subject.
I have a very simple layout containing only an empty RelativeLayout.
Once I have input form the user this relative layout is filled with square tiles to achieve a mosaic-like effect. Each tile is made by a FrameLayout containing two images (only one is drawn at any given time). It is not possible for me to put the tiles in the XML layout because I do not know in advance how many of them I will need.
In the onSizeChanged of my relative layout, I force a resize on all the tiles to fit the new size.
The code is something like this:
public void resizeTiles(int w, int h) {
int l1 = w / X; int l2 = h / Y;
int tileS = (l1 <= l2 ? l1 : l2);
android.view.ViewGroup.LayoutParams lp;
for (Tile t : myTiles) {
lp = t.getLayoutParams();
lp.width = tileS;
lp.height = tileS;
}
}
In my manifest file I have the following:
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="4"
/>
Thus, target system is 1.6.
So far so good, this is working like a charm ... but only on 2.2.
The same binary placed on emulator 2.1-update1 or previous is giving me back an empty layout (I also tried a couple of physical devices, same result).
Debugging, I tracked down the problem is in the resize; commenting out width and height assignments I see the tiles but with distorted proportions.
Any suggestion on how to make this working ?
Thanks in advance.
onSizeChanged() is called late in the layout process, once the final size has been determined. There may already have been some layout passes that have happened down through the hierarchy at that point.
Basic answer is: layout params are for telling the view's parent its layout params prior to is performing a layout. If they change, the layout must be invalidated to perform a new complete layout with the new params. You should never change these in the middle of a layout.
The best thing to do is just write your own layout manager. (If you are doing layout of tiles, RelativeLayout does a ton more stuff that you don't need, making it a lot less efficient than necessary.) It is actually not very hard to write a simple layout manager.
You can use the simple layout managers in the framework as a guide:
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/widget/AbsoluteLayout.java
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/widget/FrameLayout.java
(Note that even these are a lot more complicated than you probably need, since they are intended to be general purpose for the layouts they are implementing. We really should have an API demo of a custom layout that is truly simple.)

Categories

Resources