getLayoutParam returning width as -1 - android

I am trying to set the layout width programatically .
ViewTreeObserver vtoRecyclerView = mMainLayout.getViewTreeObserver();
vtoRecyclerView.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mMainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
ViewGroup.LayoutParams lpView = mMainLayout.getLayoutParams();
lpView.width = ViewGroup.LayoutParams.MATCH_PARENT-20;
mMainLayout.requestLayout();
}
});
but mMainLayout.getLayoutParams() is returning width as -1 .so when I set width as match_parent - 20 it becomes -21. I want to set the width as match_parent - 20.
What is wrong with the approach.

The root problem with your code here, is because you set the width with:
lpView.width = ViewGroup.LayoutParams.MATCH_PARENT-20;
while ViewGroup.LayoutParams.MATCH_PARENT is a constant.
You can find the constant on ViewGroup class
public static final int MATCH_PARENT = -1;
So that is obvious, because -1 - 20 is -21
What you can do here is, you can change the line to
lpView.width = mMainLayout.getWidth()-20;

try this.
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
ViewTreeObserver vtoRecyclerView = mMainLayout.getViewTreeObserver();
vtoRecyclerView.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mMainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
ViewGroup.LayoutParams lpView = mMainLayout.getLayoutParams();
lpView.width = width -20;
mMainLayout.requestLayout();
}
});

Try this.
ViewTreeObserver vtoRecyclerView = mMainLayout.getViewTreeObserver();
vtoRecyclerView.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if(mMainLayout.getWidth > 10 && mMainLayout.getHeight() > 10) // you can modify this value.
{
mMainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
ViewGroup.LayoutParams lpView = mMainLayout.getLayoutParams();
lpView.width = ViewGroup.LayoutParams.MATCH_PARENT-20; // This seems to be wrong;
ViewParent parent = mMainLayout.getParent();
if(parent != null) {
lpView.width = (View)parent.getWidth();
}
mMainLayout.requestLayout();
}
}
});

I had the same problem while setting width as match_parent, I had resolved this by getting the phone screen width as follows:
Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int ActualWidth=width-(`margin you set for view`);
Hope it will help :)

As ViewGroup.LayoutParams.MATCH_PARENT constant predefined numeric value is -1 so you are getting -21 as result. and what you want can be achieved by defining margin to a layout rather than using that approach.

Related

change the width & height of ImageButton at runtime in android

I have used this code to make a ImageButton & after that i want to change the size of it at run time. Both the codes the written below,
<ImageButton
android:id="#+id/btn_new"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/untitled3"
/>
public void scaler1() {
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
btn_new.setMinimumWidth(width/4);
btn_new.setMinimumHeight(height/6);
}
But it is not working please give any solution of it.
This is the actual code i'm using
public void scaler1() {
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
edit_screen.setWidth(width);
edit_screen.setHeight(height / 6);
lpsame = (LayoutParams) btn_0.getLayoutParams();
lpsame.width=width/4;
lpsame.height=height/6;
btn_0.setLayoutParams(lpsame);
LayoutParams lpedit = (LayoutParams) edit_screen.getLayoutParams();
lpedit.width=width;
lpedit.height=height/6;
LayoutParams lpequal = (LayoutParams) btn_0.getLayoutParams();
lpequal.width=width/2;
lpequal.height=height/6;
edit_screen.setLayoutParams(lpedit);
btn_2.setLayoutParams(lpsame);
btn_3.setLayoutParams(lpsame);
btn_4.setLayoutParams(lpsame);
btn_5.setLayoutParams(lpsame);
btn_6.setLayoutParams(lpsame);
btn_7.setLayoutParams(lpsame);
btn_8.setLayoutParams(lpsame);
btn_9.setLayoutParams(lpsame);
btn_add.setLayoutParams(lpsame);
btn_subtrac.setLayoutParams(lpsame);
btn_multiply.setLayoutParams(lpsame);
btn_divide.setLayoutParams(lpsame);
btn_dot.setLayoutParams(lpsame);
btn_percentage.setLayoutParams(lpsame);
btn_CA.setLayoutParams(lpsame);
btn_back.setLayoutParams(lpsame);
btn_equal.setLayoutParams(lpequal);
editParams = new RelativeLayout.LayoutParams(width, height/6);
sameparam= new RelativeLayout.LayoutParams(width/4,height/6);
equalparam= new RelativeLayout.LayoutParams(width/2,height/6);
edit_screen.setLayoutParams(editParams);
}
You can change properties of a View by using LayoutParams class
LayoutParams lp = (LayoutParams) btn_new.getLayoutParams();
lp.width = yourWidth;
lp.height = yourHeight;
btn_new.setLayoutParams(lp);
Update
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(yourWidth, yourHeight);
yourButtons.setLayoutParams(layoutParams);
You have to get an instance of your view, before changing its properties
ImageButton btn_new = (ImageButton) findViewById(R.id.btn_new);
try this:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
LayoutParams layoutParams = image_new.getLayoutParams();
layoutParams.width=width/4;
layoutParams.height=height/6;
image_new.setLayoutParams(layoutParams);

Layout params getWidth() returns zero

i have a RelativeLayout here's the code :
<RelativeLayout
android:id="#+id/camerapreview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:background="#000">
</RelativeLayout>
its a camera preview for the camera application, i set the width to match_parent.
and here is my java code :
RelativeLayout preview = (RelativeLayout) findViewById(R.id.camerapreview);
int w = preview.getWidth();
LayoutParams params = preview.getLayoutParams();
params.width = w;
params.height = w;
preview.addView(mPreview);
basically i decalaired the width of the RelativeLayout to match_parent to be dynamic to the width of any device. But i want the view to be square so i used the java code abave, but every time i ran the program this line int w = preview.getWidth(); returns zero. I must have missed something, help please :D thank you.
The size of view cannot be calculated until its parent is calculated you can force that with following code:
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int widht = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
there is three way to do this, see this link
EDIT
you can use this too.
RelativeLayout layout = (RelativeLayout) findViewById(R.id.camerapreview);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
hs.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();
}
});
this may help you...
RelativeLayout preview = (RelativeLayout) findViewById(R.id.camerapreview);
int width = getResources().getDisplayMetrics().widthPixels;
ViewGroup.LayoutParams params = preview.getLayoutParams();
params.width = width;
params.height = width;
preview.setLayoutParams(params);
here preview will occupy entire screen width... and it will be square shaped...
Layout has width 'match parent' . So if it hasn't views (is empty) width = 0.
Solution:
Add views to layout
Or set width to 'fill parent'

Why does getWidth() is larger than getLayoutParams().width sometimes?

My code for fixing ImageView:
private void fixImageWidth() {
int parentHeight = getHeight();
if (parentHeight == 0 || getParent() == null)
return;
Drawable drawable = image.getDrawable();
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) image.getLayoutParams();
if (drawable != null) {
int height = drawable.getIntrinsicHeight();
int width = drawable.getIntrinsicWidth();
lp.width = (int) ((float)(parentHeight - lp.topMargin * 2) / height * width);
} else {
lp.width = LayoutParams.WRAP_CONTENT;
}
image.requestLayout();
}
But sometimes actually image bounds is not changed. Below you could see HierarchyViewer properties of that object:
EDIT:
After I lot for debugging I determined, sometimes requestLayout don't remeasure image view. How does this happens?
EDIT:
I found solution, but still don't know reason. Solution is below:
image.post(new Runnable() {
#Override
public void run() {
image.requestLayout();
}
});
Any ideas?
Because getWidth() and getLayoutParams().width are different things. 1st relates to the View, the second is a layout request to the parent. If the parent cannot match the request the View maybe laid out with a different width. In this case you have requested MATCH_PARENT in the layout height and since an ImageView has a default scaleType of FIT_CENTER therefore content aspect ratio is maintained so the width will change.

How can I get a width/height of Dialog with FILL_PARENT layout?

I have an activity with
android:theme="#android:style/Theme.Dialog"
to show it as float window. Also I have a line
getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
And I need a width/height of this window to show content correctly.
I've tested four options and did not get an answer:
//1
int width = getWindowManager().getDefaultDisplay().getWidth();
//2
int width = getWindow().getDecorView().getWidth();
//3
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
//4
int width = getWindow().getAttributes().width;
Thanks!
use this function:
private int getting_screen_width(Dialog dialog)
{
DisplayMetrics dm = new DisplayMetrics();
dialog.getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
String width = ""+dm.widthPixels ;
dm = null;
return (Integer.parseInt(width));
this return the value of the screen width

How to resize a custom view programmatically?

I am coding a custom view, extended from RelativeLayout, and I want to resize it programmatically, How can I do?
the custom view Class is something like:
public ActiveSlideView(Context context, AttributeSet attr){
super(context, attr);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(inflater != null){
inflater.inflate(R.layout.active_slide, this);
}
Android throws an exception if you fail to pass the height or width of a view.
Instead of creating a new LayoutParams object, use the original one, so that all other set parameters are kept. Note that the type of LayoutParams returned by getLayoutParams is that of the parent layout, not the view you are resizing.
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) someLayout.getLayoutParams();
params.height = 130;
someLayout.setLayoutParams(params);
this.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, theSizeIWant));
Problem solved!
NOTE: Be sure to use the parent Layout's LayoutParams. Mine is LinearLayout.LayoutParams!
This works for me:
ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = customHeight;
layout.requestLayout();
In Kotlin, you can use the ktx extensions:
yourView.updateLayoutParams {
height = <YOUR_HEIGHT>
}
For what it's worth, let's say you wanted to resize the view in device independent pixels (dp): -
You need to use a method called applyDimension, that's a member of the class TypedValue to convert from dp to pixels. So if I want to set the height to 150dp (say) - then I could do this:
float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, getResources().getDisplayMetrics());
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) someLayout.getLayoutParams();
params.height = (int) pixels;
someLayout.setLayoutParams(params);
where the expression: getResources().getDisplayMetrics() gets the screen density/resolution
Here's a more generic version of the solution above from #herbertD :
private void resizeView(View view, int newWidth, int newHeight) {
try {
Constructor<? extends LayoutParams> ctor = view.getLayoutParams().getClass().getDeclaredConstructor(int.class, int.class);
view.setLayoutParams(ctor.newInstance(newWidth, newHeight));
} catch (Exception e) {
e.printStackTrace();
}
}
try a this one:
...
View view = inflater.inflate(R.layout.active_slide, this);
view.setMinimumWidth(200);
I used this way to increase width of custom view
customDrawingView.post(new Runnable() {
#Override
public void run() {
View view_instance = customDrawingView;
android.view.ViewGroup.LayoutParams params = view_instance
.getLayoutParams();
int newLayoutWidth = customDrawingView
.getWidth()
+ customDrawingView.getWidth();
params.width = newLayoutWidth;
view_instance.setLayoutParams(params);
screenWidthBackup = params.width;
}
});
With Kotlin and using dp unit:
myView.updateLayoutParams {
val pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200f, context.resources.displayMetrics)
height = pixels.toInt()
}
I solved it this way.. I have basically a simple view inside xml file.
View viewname = findViewById(R.id.prod_extra);
prodExtra.getLayoutParams().height=64;
If you have only two or three condition(sizes) then you can use #Overide onMeasure like
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
And change your size for these conditions in CustomView class easily.
This is how it can be done in Kotlin:
updateLayoutParams:
val view = layoutInflater.inflate(R.layout.cell, binding.ssss, false).apply {
id = View.generateViewId()
updateLayoutParams {
height = 200
width = 400
}
}
binding.ssss.addView(view)
OR
layoutParams:
val view = layoutInflater.inflate(R.layout.cell, binding.ssss, false).apply {
id = View.generateViewId()
layoutParams.width = 200
layoutParams.height = 200
}
binding.ssss.addView(view)
if you are overriding onMeasure, don't forget to update the new sizes
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(newWidth, newHeight);
}
This is how I achieved this. In Sileria answer he/she did the following:
ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = customHeight;
layout.requestLayout();
This is correct, but it expects us to give the height in pixels, but I wanted to give the dp I want the height to be so I added:
public int convertDpToPixelInt(float dp, Context context) {
return (int) (dp * (((float) context.getResources().getDisplayMetrics().densityDpi) / 160.0f));
}
So it will look like this:
ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = convertDpToPixelInt(50, getContext());
layout.requestLayout();
This is what I did:
View myView;
myView.getLayoutParams().height = 32;
myView.getLayoutParams().width = 32;
If there is a view group that this view belongs to, you may also need to call yourViewGroup.requestLayout() for it to take effect.
fun View.setSize(width: Int, height: Int) {
updateLayoutParams {
this.width = width
this.height = height
}
}

Categories

Resources