HeaderView和Footer视图未添加到ListView

时间:2015-03-13 20:20:56

标签: android android-listview

我无法添加页眉或页脚,尝试了不同的示例。 我片段的布局是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

我的empty_header布局:

<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#000000"
    android:layout_width="match_parent"
    android:layout_height="254dp" />

我的片段类代码:

public class ListTestFragment extends Fragment {
    ListView mListView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.list_test, parent, false);
        mListView = (ListView) rootView.findViewById(R.id.list_view);
        String[] names = new String[] { "Linux", "Windows7", "Eclipse", "Suse",
            "Ubuntu", "Solaris", "Android", "iPhone", "Linux", "Windows7",
            "Eclipse", "Suse", "Ubuntu", "Solaris", "Android", "iPhone" };
        View headerView = inflater.inflate(R.layout.empty_header, null);
        View footerView = inflater.inflate(R.layout.empty_header, null);
        mListView.addHeaderView(headerView);
        mListView.addFooterView(footerView);
        mListView.setAdapter(new ArrayAdapter<>(getActivity(),
            android.R.layout.simple_list_item_1, names));
        return rootView;
    }
}

没有单一的效果,只显示屏幕上的项目列表视图。

1 个答案:

答案 0 :(得分:1)

您需要在充气时指定父级:

View headerView = inflater.inflate(R.layout.empty_header, mListView, false);