Michael Jones Michael Jones - 1 year ago 58
Android Question

Correct way of changing View's Height and Width Android

very new to android here! I am basically confused on how to change a View's Height and Width. Currently I have such (snippets):

XML (Uses Relative layouts)

android:background="@color/colorAccent" />


protected void onCreate(Bundle savedInstanceState) {

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
int screenWidth = size.x;
int screenHeight = size.y;

final float pixelToDp = getResources().getDisplayMetrics().density;
int screenHeightDp = (int) (screenHeight * pixelToDp + 0.5f);
int screenWidthDp = (int) (screenWidth * pixelToDp + 0.5f);

View view = findViewById(R.id.homeBackgroundTop);
view.setLayoutParams(new RelativeLayout.LayoutParams(screenWidthDp, screenHeightDp));


The problem is it is raising the follow FATAL ERROR:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setLayoutParams(android.view.ViewGroup$LayoutParams)' on a null object reference

Now my question is, how can I correctly change a View's Height and Width programmatically? I have looked on many other SO answers, but none of them seem to work for me.

P.S. What exactly is
referring to? If I am trying to change a View, why would I be calling a Layout? Why does it sometimes also contain
? Lastly, what exactly is LayoutParams? If you have links to any of these questions, it would be greatly appreciated :) Thank you for your help!

Answer Source

Your setContentView(R.layout.activity_main); has not been called before you make your call to findViewById(). Therefore no view can be found because your views have not been attached to your activity yet.

Put setContentView(R.layout.activity_main); at the beginning of onCreate or at least before you call findViewById().

protected void onCreate(Bundle savedInstanceState) {



To answer your P.S. the RelativeLayout.LayoutParams allows you to set the basic layout parameters like height and width for the view object. Your particular view (Button or TextView, etc...) likely inherits from either a LinearLayout or a RelativeLayout view. The LayoutParams are apparently specific to the different Layout type (Relative vs Linear). I am looking around for a more concrete answer that question for myself at the moment. Let me know if you find anything on it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download