androidresizefragmentviewgroup

'android' resize a view inside a fragment


I'm struggling with programmatically resize a view inside a fragment, this Fragment is also in a FragmentStatePagerAdapter to cycling with another two views.

I have declared and instantiated the views as I always did

then I have this method to apply resizing on each view:

private void dimensioniEmargini(View view, int width, int height, int marginLeft, int marginTop, int marginBotton, int marginRight) {

        RelativeLayout.LayoutParams parametri;
        parametri = (RelativeLayout.LayoutParams) view.getLayoutParams();
        parametri.height = height;
        parametri.width = width;
        parametri.leftMargin = marginLeft;
        parametri.topMargin = marginTop;
        parametri.bottomMargin = marginBotton;
        parametri.rightMargin = marginRight;
        view.setLayoutParams(parametri);

    }

My problem is: if I call it from onCreateView it works perfectly but, if I call from another method (inside the same class), like the one below (where I give values just to try it out)

public void aggiornaDimensioni(String _query) {

        dimensioniEmargini(barraCorretto, 45, 100, 0, 0, 0, 0);

    }

I obtain a null pointer exception:

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

I need to resize from a method because it is called from parent activity and is meant to change size according to database querying.

How can I fix it?


Solution

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

    This means that you're calling getLayoutParams() on a null View object. So here:

    parametri = (RelativeLayout.LayoutParams) view.getLayoutParams();
    

    view is null. So whatever you pass in during onCreateView is fine, but barraCorretto is null when you call it from that other function.

    Remember a Fragment has to have gone through a layout (through onCreateView) before you can do getView(), and Fragments can be destroyed and recreated.