Changing LayoutParams programmatically has no effect in Android. Why? - android

I have a custom view, derived from Button, which I want to position at runtime, relative to another view. Because I don't know that other view's position yet when my view is being inflated (because layouting hasn't started), I leverage the onSizeChanged handler to set my view's position relative to the other view.
In onSizeChanged:
LayoutParams lp = new LayoutParams(this.getMeasuredWidth(), this.getMeasuredHeight());
lp.leftMargin = x;
lp.topMargin = y;
this.setLayoutParams(lp);
forceLayout();
That, however, has no effect. How come?

Some things to consider:
Are you sure this code is being executed?
Have you examined the UI in hierarchyviewer to see if the margins are being set but they are simply not having the visual effect you expect?
Are you sure this isn't better handled just via a RelativeLayout?
Have you tried modifying the existing LayoutParams rather than replacing it?

Related

After changing a property on a LayoutParams object, do I need to call setLayoutParams again?

I have a View (containing an ad) that I need to scale to fit the screen width at a certain point in time (after the ad is loaded). So I have a method setHeight(myView) that calculates the correct height for the given screen width and changes the LayoutParams of the View accordingly. The crucial part of the code is this:
LayoutParams params = myView.getLayoutParams();
int width = myView.getWidth();
if (params != null && width > 0) {
params.height = (int) Math.round(ratio * width);
}
This seems to work for the most part, but sometimes the view is not scaled. It seems to only consistenly work if I add the following line at the bottom:
myView.setLayoutParams(params);
This seems to make sense, too, since Android Views call requestLayout() in their setLayoutParams() method. Conversely, I see no way how a change in a public field (params.height) would trigger a layout change.
On the other hand, I repeatedly find tutorials on the net where the params are simply changed and then not set to the view again.
So, my question is: Is it correct that, to immediately update the layout after changing a property of the LayoutParams, I need to call setLayoutParams again? And that simply changing the property will only lead to a layout change at some later point in time when the layout change is triggered from elsewhere?
A change to the layout params only take effect on the next layout pass.
requestLayout() schedules a layout pass
setLayoutParams() calls requestLayout() as you have observed
Sometimes a layout pass is scheduled by some other means. For example, immediately after inflation the layout params have also been inflated and the measure/layout message has just been posted to the UI thread message queue for later processing.
So, to be safe, call requestLayout() always after touching the layout params. setLayoutParams() works, too, though it's not strictly necessary when modifying the params in-place.
In Kotlin you can use KTX extension to update LayoutParams
view.updateLayoutParams { height = newValue }

setX() and setY() conflict with align rule in relative layout

now I am implement a hard code of a custom relative layout, the problem is, when I use parameter of relative layout, it works well. But once I add setX and setY method, they conflict. What I actually want in my code is to dynamically set the view one by one according to the first view's position.
Here when I set the X to 50, get 50 width disappeared in the right side where the mMapView2 keep his original place.
To solve this problem the only method I could do now is to make my code tedious, cos i have many views inside relative layout here.
MapView mMapView1 = new MapView(getActivity());
mMapView1.setX(50);
mMapView1.setId(1);
LayoutParams mLayoutParams1 = new LayoutParams(screenWidth/2, screenHeight/3);
mRelativeLayout.addView(mMapView1, mLayoutParams1);
MapView mMapView2 = new MapView(getActivity());
mMapView2.setId(2);
LayoutParams mLayoutParams2 = new LayoutParams(screenWidth/2, screenHeight/3);
mLayoutParams2.addRule(RelativeLayout.RIGHT_OF,1);
mRelativeLayout.addView(mMapView2, mLayoutParams2);

Unable to make child view wider than parent in Android Layout

I'm moving a view after an animation completes(to slide out a menu from the left). However, I don't seem to be able to achieve the effect I'm looking for. What I'd like is for the view to extend to the right past the parent's bounds, like this:
but what's happening is actually this:
The view resets itself to stay within the bounds of the parent. Even if I set an absolute pixel value (by looking at the display's width, or even a randomly large value).
The reason I need to do this is detailed in this SO question about a view's actual position after an animation has completed:
TranslateAnimated ImageView not clickable after animation [Android]
any thoughts? Thanks!
So, here is a related question. It explains how to move a view out of the screen.
I had same problem and I found the solution. I hope it can be helpful.
You need to set fixed width if you want to achieve this effect. To find real width of the view you need to measure it.
So full solution is:
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int height = view.getMeasuredHeight();
int width = view.getMeasuredWidth();
view.setLayoutParams(new LinearLayout.LayoutParams(width, height));
(Use LayoutParams of the type corresponding the type of the parent layout)

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.

Categories

Resources