android – 如何将listView标头添加为自定义布局

我想在listView中添加标题我尝试这样我在这里缺少的ids很好.
我在片段中使用它.

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)
最佳答案
我们可以向ListView添加标题,如下所示:

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

但是,根据您的错误,您可能已经在xml和java文件中使用了相对布局,您正在使用LinearLayout.

您还必须将ListView初始化为:

lv=(ListView)findViewById(R.id.yourlistview);`

转载注明原文:android – 如何将listView标头添加为自定义布局 - 代码日志