0

I was trying to change the height of a fragment programmatically.

I could get the result in XML having the fragment layout height to 650dp;

But I want to change that dynamically.

Inside the onCreateView of fragment I wrote the below code which throws a NullPointerException -

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_group_info, container, false);
    try {
        ViewGroup.LayoutParams params = v.getLayoutParams();
        params.height = 610;
        v.setLayoutParams(params);
    } catch (Exception e) {
        Log.d("ListView1", "GroupInfoFragment Height Exception: " + e.toString());
    }
    mListView = (ListView) v.findViewById(android.R.id.list);
    rv =v;
    return v;
}

the Exception -

GroupInfo Fragment Height Exception: java.lang.NullPointerException: 
Attempt to invoke virtual method 'android.view.View android.app.Fragment.getView()' 
on a null object reference
Pradyut Bhattacharya
  • 5,440
  • 13
  • 53
  • 83
  • 1
    You need to listen until the view is inflated, only then change its parameters. Check this question http://stackoverflow.com/questions/7733813/how-can-you-tell-when-a-layout-has-been-drawn – lxknvlk Dec 09 '16 at 16:20

1 Answers1

0

Initialize a global View(rv below) variable and initialize on the Fragment onCreateView -

View rv;
...
...
...


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{

    View v = inflater.inflate(R.layout.fragment_group_info, container, false);


    rv =v;
    return v;
}

on the fragment onActivityCreated method change the height -

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    try {
        ViewGroup.LayoutParams params = rv.getLayoutParams();
        params.height = 1200;
        rv.setLayoutParams(params);
    } catch (Exception e) {
        Log.d("ListView1", "2 GroupInfoFragment Height Exception: " + e.toString());
    }
}
Pradyut Bhattacharya
  • 5,440
  • 13
  • 53
  • 83