Michael Jones Michael Jones - 5 months ago 15
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)

<View
android:id="@+id/homeBackgroundTop"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_centerHorizontal="true"
android:background="@color/colorAccent" />


Java

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
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));

setContentView(R.layout.activity_main);
}


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
RelativeLayout.LayoutParams
referring to? If I am trying to change a View, why would I be calling a Layout? Why does it sometimes also contain
LinearLayout
? 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

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ...
}

EDIT

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.

Comments