片段更改高度的片段

时间:2016-12-09 14:05:36

标签: android android-layout android-fragments layout

我试图以编程方式更改片段的高度。

我可以在XML中获得片段布局高度为650dp的结果;

但我想动态地改变它。

在片段的onCreateView里面我写下了抛出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;
}

例外 -

GroupInfo Fragment Height Exception: java.lang.NullPointerException: 
Attempt to invoke virtual method 'android.view.View android.app.Fragment.getView()' 
on a null object reference

1 个答案:

答案 0 :(得分:0)

初始化全局视图(rv以下)变量并初始化片段 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;
}

片段 onActivityCreated 方法更改高度 -

@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());
    }
}