How add listView header as a custom layout

2019-07-07 01:44发布

I want to add header in listView i try like this what i am missing here ids are fine. I am using this in fragment.

ListView lv;

LinearLayout header = (LinearLayout) rootView.findViewById(R.id.header_layout);

lv.addHeaderView(header);
// APP is crashing here?

Logcat

java.lang.ClassCastException: android.widget.AbsListView$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
            at android.widget.RelativeLayout$DependencyGraph.findRoots(RelativeLayout.java:1732)
            at android.widget.RelativeLayout$DependencyGraph.getSortedViews(RelativeLayout.java:1677)
            at android.widget.RelativeLayout.sortChildren(RelativeLayout.java:381)
            at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:389)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:17547)

3条回答
祖国的老花朵
2楼-- · 2019-07-07 02:04

We Can add header to ListView as below :

LayoutInflater myinflater = getLayoutInflater();
ViewGroup myHeader = (ViewGroup)myinflater.inflate(R.layout.headerlayout, myListView, false);
myListView.addHeaderView(myHeader, null, false);

But, As per your error you might have taken Relative Layout in your xml and in your java file, You are using LinearLayout.

You also have to initialize your ListView as :

lv=(ListView)findViewById(R.id.yourlistview);`
查看更多
太酷不给撩
3楼-- · 2019-07-07 02:19

You need to initialise list view before you set header view.

something like this

lv = (ListView) findViewById(R.id.list);

then you can add the header view after inflating header view.

View head = (View) getActivity().getLayoutInflater().inflate(R.layout. header_layout, null);
lv.addHeaderView(header);
查看更多
相关推荐>>
4楼-- · 2019-07-07 02:26

Add this to your Adapter :

 @Override
    public boolean isEmpty() {
        return false;
    }

Add this to your adapter if you have SectionedBaseAdapter:

 @Override
        public int getCountForSection(int section) {

            switch (section) {

                case 0:
                    return listPOJOInAdapter== null ? 1 : listPOJOInAdapter.size();

            }

            return 1;
        }

And after adding HeaderView to ListView, Try to set Adapter of ListView.

Hopefully it will help you ! Let me know if you get success !

查看更多
登录 后发表回答