Android set height and width of Custom view programmatically
Asked Answered
P

10

179

I have created a custom view named Graphview . Here is the structure for the GraphView class.

public class GraphView extends View {

    public GraphView(Context context, float[] values, String title, String[] horlabels, String[] verlabels, boolean type) {
        super(context);
                ........
   }

   ..................
   .................
}

I have added the view in a tablerow using addview(). It is working fine. Now I want to set height and width for the GraphView. How to do that?

Peart answered 18/2, 2011 at 14:1 Comment(0)
E
186

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.

Electropositive answered 18/2, 2011 at 14:15 Comment(3)
Would be helpful to know which LayoutParams you are importing there.Interfere
The LayoutParams should be from the layout where the graphView is placed. For example if in the XML layout file graphView is placed inside RelativeLayout, then you should use new RelativeLayout.LayoutParams(width, height)Ruvolo
What if the graphView inside a ScrollView in Kotlin?Wollongong
R
244

You can set height and width like this:

myGraphView.setLayoutParams(new LayoutParams(width, height));
Rightward answered 18/2, 2011 at 14:9 Comment(7)
You should make sure the LayoutParam class you use is from the correct parent Layout class. For example, if your GraphView is contained in a LinearLayout, you need to use the LinearLayout.LayoutParams class.Uvea
This also does work and ensures you use the correct LayoutParams class: simply do myGraphView.getLayoutParams().height = 100;.Thynne
Generally making absolute statements with hardcoded meaningless numbers leads to trouble. Better to make relative statements as much as possible, e.g. with fill_parent etc.Connubial
If you do this.getLayoutParams().height = 100, make sure to follow it by this.setLayoutParams(this.getLayoutParams()), otherwise it will not do anything (useful).Remediosremedy
I think it's odd that this answer is getting more points. While it's easier it's much less modular; if you'd like to use your view in a different place you'd need to hardcode those width/height values there as well. Be careful about using this.Dygall
Thanks @Uvea for pointing that out. It seems odd that I need to use the parent view' class (RelativeLayout in my case) instead of the parent class of my custom view (SurfaceView in my case) thoughDight
We do need to calculate the size of a view programmatically when the default params do not fit the need of program. That why we need this answer. Thank you Eric Nordvik, you helped a lot.Younts
E
186

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.

Electropositive answered 18/2, 2011 at 14:15 Comment(3)
Would be helpful to know which LayoutParams you are importing there.Interfere
The LayoutParams should be from the layout where the graphView is placed. For example if in the XML layout file graphView is placed inside RelativeLayout, then you should use new RelativeLayout.LayoutParams(width, height)Ruvolo
What if the graphView inside a ScrollView in Kotlin?Wollongong
G
95

you can set the height and width of a view in a relative layout like this

ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = 130;
view.setLayoutParams(params);
Gurrola answered 12/6, 2013 at 13:22 Comment(5)
you do not need to set layoutparam again. It gets reflected automatically. This is the advantage of object oriented approach.Colenecoleopteran
@Colenecoleopteran the call to setLayoutParams() is required because it invokes other methods such as resolveLayoutParams() and requestLayout()Interline
giving exception as in onCreate getLayoutParams() is null value.So params.height cause exceptionRope
You should refer the view for which you have to set the height. Check if you are pointing to the same viewGurrola
Getting the layoutParams at a view's initiation will be a NPE, please explain at what point to you run this?Solace
E
31

If you're using Kotlin, you can also use the following code which applies your given lambda on the current layout params:

someView.updateLayoutParams {
    height = 200
}
Elihu answered 7/12, 2021 at 13:52 Comment(0)
S
30

On Kotlin you can set width and height of any view directly using their virtual properties:

someView.layoutParams.width = 100
someView.layoutParams.height = 200
Sewerage answered 15/10, 2019 at 15:2 Comment(2)
This doesn't work because it won't update the UIColp
you might need to add someView.requestLayout() right after that to apply the changes.Zooplasty
S
4
spin12.setLayoutParams(new LinearLayout.LayoutParams(200, 120));

spin12 is your spinner and 200,120 is width and height for your spinner.

Shaff answered 21/5, 2014 at 10:11 Comment(0)
F
3

This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout.

someView.layoutParams = LinearLayout.LayoutParams(100, 200)

This allows to set the width and height (100 and 200) in a single line.

Fleshly answered 17/8, 2018 at 13:46 Comment(0)
T
1

Typical real-world example:

in a Fragment:

private LinearLayout images;
...

float dpf = TypedValue.applyDimension(
  TypedValue.COMPLEX_UNIT_DIP, 69, getResources().getDisplayMetrics());

    for (int i = 0; i < 10; i++) {
        SpecialImage s = new SpecialImage(getActivity());
        images.addView(s);
        s.setLayoutParams(new LinearLayout.LayoutParams(
         (int) dpf, LinearLayout.LayoutParams.MATCH_PARENT));
    }
  1. useless unless use DIP conversion
  2. this usually happens in fragments, notice getActivity()
  3. you're usually adding a few into a linear layout or similar
  4. typically one dimension is "fill parent"
  5. you must use the "correct" LayoutParams (ie, LinearLayout.LayoutParams in the example
Thuja answered 19/6, 2022 at 19:31 Comment(0)
O
0

Adding on to the solution by @MorganWilde. You can use the following code if you want to use WRAP_CONTENT/MATCH_PARENT.

someView.layoutParams =
   LinearLayout.LayoutParams(
     ViewGroup.LayoutParams.MATCH_PARENT,
     ViewGroup.LayoutParams.WRAP_CONTENT)
Outrush answered 15/3, 2022 at 1:43 Comment(0)
F
-1

here this class take care of everything you need for working with views programmatically

public class LayoutHelper {

public static final int MATCH_PARENT = -1;
public static final int WRAP_CONTENT = -2;

private static int getSize(float size) {
    return (int) (size < 0 ? size : AndroidUtilities.dp(size));
}

public static ScrollView.LayoutParams createScroll(int width, int height, int gravity) {
    return new ScrollView.LayoutParams(getSize(width), getSize(height), gravity);
}

public static ScrollView.LayoutParams createScroll(int width, int height, int gravity, float leftMargin, float topMargin, float rightMargin, float bottomMargin) {
    ScrollView.LayoutParams layoutParams = new ScrollView.LayoutParams(getSize(width), getSize(height), gravity);
    layoutParams.leftMargin = AndroidUtilities.dp(leftMargin);
    layoutParams.topMargin = AndroidUtilities.dp(topMargin);
    layoutParams.rightMargin = AndroidUtilities.dp(rightMargin);
    layoutParams.bottomMargin = AndroidUtilities.dp(bottomMargin);
    return layoutParams;
}

public static FrameLayout.LayoutParams createFrame(int width, float height, int gravity, float leftMargin, float topMargin, float rightMargin, float bottomMargin) {
    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(getSize(width), getSize(height), gravity);
    layoutParams.setMargins(AndroidUtilities.dp(leftMargin), AndroidUtilities.dp(topMargin), AndroidUtilities.dp(rightMargin), AndroidUtilities.dp(bottomMargin));
    return layoutParams;
}

public static FrameLayout.LayoutParams createFrame(int width, int height, int gravity) {
    return new FrameLayout.LayoutParams(getSize(width), getSize(height), gravity);
}

public static FrameLayout.LayoutParams createFrame(int width, float height) {
    return new FrameLayout.LayoutParams(getSize(width), getSize(height));
}

public static RelativeLayout.LayoutParams createRelative(float width, float height, int leftMargin, int topMargin, int rightMargin, int bottomMargin, int alignParent, int alignRelative, int anchorRelative) {
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(getSize(width), getSize(height));
    if (alignParent >= 0) {
        layoutParams.addRule(alignParent);
    }
    if (alignRelative >= 0 && anchorRelative >= 0) {
        layoutParams.addRule(alignRelative, anchorRelative);
    }
    layoutParams.leftMargin = AndroidUtilities.dp(leftMargin);
    layoutParams.topMargin = AndroidUtilities.dp(topMargin);
    layoutParams.rightMargin = AndroidUtilities.dp(rightMargin);
    layoutParams.bottomMargin = AndroidUtilities.dp(bottomMargin);
    return layoutParams;
}

public static RelativeLayout.LayoutParams createRelative(int width, int height, int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
    return createRelative(width, height, leftMargin, topMargin, rightMargin, bottomMargin, -1, -1, -1);
}

public static RelativeLayout.LayoutParams createRelative(int width, int height, int leftMargin, int topMargin, int rightMargin, int bottomMargin, int alignParent) {
    return createRelative(width, height, leftMargin, topMargin, rightMargin, bottomMargin, alignParent, -1, -1);
}

public static RelativeLayout.LayoutParams createRelative(float width, float height, int leftMargin, int topMargin, int rightMargin, int bottomMargin, int alignRelative, int anchorRelative) {
    return createRelative(width, height, leftMargin, topMargin, rightMargin, bottomMargin, -1, alignRelative, anchorRelative);
}

public static RelativeLayout.LayoutParams createRelative(int width, int height, int alignParent, int alignRelative, int anchorRelative) {
    return createRelative(width, height, 0, 0, 0, 0, alignParent, alignRelative, anchorRelative);
}

public static RelativeLayout.LayoutParams createRelative(int width, int height) {
    return createRelative(width, height, 0, 0, 0, 0, -1, -1, -1);
}

public static RelativeLayout.LayoutParams createRelative(int width, int height, int alignParent) {
    return createRelative(width, height, 0, 0, 0, 0, alignParent, -1, -1);
}

public static RelativeLayout.LayoutParams createRelative(int width, int height, int alignRelative, int anchorRelative) {
    return createRelative(width, height, 0, 0, 0, 0, -1, alignRelative, anchorRelative);
}

public static LinearLayout.LayoutParams createLinear(int width, int height, float weight, int gravity, int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getSize(width), getSize(height), weight);
    layoutParams.setMargins(AndroidUtilities.dp(leftMargin), AndroidUtilities.dp(topMargin), AndroidUtilities.dp(rightMargin), AndroidUtilities.dp(bottomMargin));
    layoutParams.gravity = gravity;
    return layoutParams;
}

public static LinearLayout.LayoutParams createLinear(int width, int height, float weight, int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getSize(width), getSize(height), weight);
    layoutParams.setMargins(AndroidUtilities.dp(leftMargin), AndroidUtilities.dp(topMargin), AndroidUtilities.dp(rightMargin), AndroidUtilities.dp(bottomMargin));
    return layoutParams;
}

public static LinearLayout.LayoutParams createLinear(int width, int height, int gravity, int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getSize(width), getSize(height));
    layoutParams.setMargins(AndroidUtilities.dp(leftMargin), AndroidUtilities.dp(topMargin), AndroidUtilities.dp(rightMargin), AndroidUtilities.dp(bottomMargin));
    layoutParams.gravity = gravity;
    return layoutParams;
}

public static LinearLayout.LayoutParams createLinear(int width, int height, float leftMargin, float topMargin, float rightMargin, float bottomMargin) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getSize(width), getSize(height));
    layoutParams.setMargins(AndroidUtilities.dp(leftMargin), AndroidUtilities.dp(topMargin), AndroidUtilities.dp(rightMargin), AndroidUtilities.dp(bottomMargin));
    return layoutParams;
}

public static LinearLayout.LayoutParams createLinear(int width, int height, float weight, int gravity) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getSize(width), getSize(height), weight);
    layoutParams.gravity = gravity;
    return layoutParams;
}

public static LinearLayout.LayoutParams createLinear(int width, int height, int gravity) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getSize(width), getSize(height));
    layoutParams.gravity = gravity;
    return layoutParams;
}

public static LinearLayout.LayoutParams createLinear(int width, int height, float weight) {
    return new LinearLayout.LayoutParams(getSize(width), getSize(height), weight);
}

public static LinearLayout.LayoutParams createLinear(int width, int height) {
    return new LinearLayout.LayoutParams(getSize(width), getSize(height));
}

}

and you can use it like this:

        frameLayout.addView(
        emptyLayout,
        LayoutHelper.createFrame(
            LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT,
            Gravity.CENTER
        )
    );
Floater answered 20/12, 2022 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.