Paymon Wang-Lotfi
Paymon Wang-Lotfi

Reputation: 555

How do I change the dimensions of a View programmatically?

I just want an empty view with certain dimensions. I declare the reference variable here:

public static View sv;

I instantiate the view in the onCreate method of my activity:

sv = new View(this);

and then attempt to set the dimensions right below it:

sv.setLayoutParams(new FrameLayout.LayoutParams(100, 100));

but when I call sv.getWidth() and sv.getHeight(), they still return 0

Upvotes: 0

Views: 84

Answers (1)

Busata
Busata

Reputation: 1039

The height and width only will have value after of the OnCreate() and OnResume(). Try get height and width after this methods.


UPDATED

You can use a layout listener for this, depending on your goals. For example, in onCreate():

final View view = findViewById(android.R.id.view);
        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                //Now you can change the dimensions
            }
        });

Upvotes: 1

Related Questions