How to resize a custom view programmatically?

AndroidResize

Android Problem Overview


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 Solutions


Solution 1 - Android

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);

Solution 2 - Android

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!

Solution 3 - Android

This works for me:

ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = customHeight;
layout.requestLayout();

Solution 4 - Android

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

Solution 5 - Android

In Kotlin, you can use the ktx extensions:

yourView.updateLayoutParams {
   height = <YOUR_HEIGHT>
}

Solution 6 - Android

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(); 
    }
}

Solution 7 - Android

try a this one:

...
View view = inflater.inflate(R.layout.active_slide, this);
view.setMinimumWidth(200);

Solution 8 - Android

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;
							}
						});

Solution 9 - Android

With Kotlin and using dp unit:

myView.updateLayoutParams {
    val pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200f, context.resources.displayMetrics)
    height = pixels.toInt()
}

Solution 10 - Android

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;

Solution 11 - Android

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.

Solution 12 - Android

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)

PS. Vel_daN: Love what You DO .

Solution 13 - Android

if you are overriding onMeasure, don't forget to update the new sizes

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(newWidth, newHeight);
}

Solution 14 - Android

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();

Solution 15 - Android

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionherbertDView Question on Stackoverflow
Solution 1 - AndroidsmisiewiczView Answer on Stackoverflow
Solution 2 - AndroidherbertDView Answer on Stackoverflow
Solution 3 - AndroidSileriaView Answer on Stackoverflow
Solution 4 - AndroidDanieldView Answer on Stackoverflow
Solution 5 - AndroidPhilView Answer on Stackoverflow
Solution 6 - AndroidatrouttView Answer on Stackoverflow
Solution 7 - Androidzed_0xffView Answer on Stackoverflow
Solution 8 - AndroidAkhilGiteView Answer on Stackoverflow
Solution 9 - AndroidSkouaView Answer on Stackoverflow
Solution 10 - AndroidDazzleGifts AppsView Answer on Stackoverflow
Solution 11 - AndroidXar-e-ahmer KhanView Answer on Stackoverflow
Solution 12 - AndroidВладислав ШестернинView Answer on Stackoverflow
Solution 13 - AndroidXurajBView Answer on Stackoverflow
Solution 14 - AndroidClassAView Answer on Stackoverflow
Solution 15 - Androidus_davidView Answer on Stackoverflow