Android Set Height and Width of Custom View Programmatically

Android set height and width of Custom view programmatically

If you know the exact size of the view, just use setLayoutParams():

graphView.setLayoutParams(new LayoutParams(width, height));

Or in Kotlin:

graphView.layoutParams = LayoutParams(width, height)

However, if you need a more flexible approach you can override onMeasure() to measure the view more precisely depending on the space available and layout constraints (wrap_content, match_parent, or a fixed size). You can find more details about onMeasure() in the android docs.

How to resize a custom view programmatically?

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!

How to set width and height for custom view in programmatically?

Override the onMeasure() method, have a look here

Set View Width Programmatically

This code let you fill the banner to the maximum width and keep the ratio.
This will only work in portrait. You must recreate the ad when you rotate the device.
In landscape you should just leave the ad as is because it will be quite big an blurred.

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
double ratio = ((float) (width))/300.0;
int height = (int)(ratio*50);

AdView adView = new AdView(this,"ad_url","my_ad_key",true,true);
LinearLayout layout = (LinearLayout) findViewById(R.id.testing);
mAdView.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,height));
adView.setAdListener(this);
layout.addView(adView);

Proper way override fixed size custom view

After lots of trial and error and doing research work, final found answer.

You have set measurements for layout but not for child view, so for that you need to put this in onMeasure method,

        super.onMeasure(
MeasureSpec.makeMeasureSpec(desiredWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(desiredHeight, MeasureSpec.EXACTLY));

Reference link : Inflated children of custom LinearLayout don't show when overriding onMeasure

And finally it's working :)



Related Topics



Leave a reply



Submit