【问题标题】:Android: Can't add header to ListView (LinearLayout can't be cast in AbsListView)Android:无法将标题添加到ListView(无法在AbsListView中投射LinearLayout)
【发布时间】:2014-11-07 13:14:20
【问题描述】:

我正在尝试将带有 ImageView 的标题添加到我的 ListView。我将 ImageView 放在 XML 布局中,在 Activity 中我正在扩展布局并将其添加到 ListView 标头,但是当我运行应用程序时它崩溃说 "java.lang.ClassCastException: android.widget.LinearLayout$ LayoutParams 无法转换为 android.widget.AbsListView$LayoutParams"

我尝试将 LinearLayout 更改为其他布局,但仍然收到此错误消息。有什么想法吗?

list_header_banner.xml 代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/publicidadeView"
    android:layout_marginTop="15dp"
    android:layout_marginBottom="15dp"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:scaleType="fitXY"
    android:clickable="true"
    />
</LinearLayout>

活动膨胀代码示例

ListView list = (ListView)findViewById(R.id.lvResults);
View headerView = View.inflate(this, R.layout.list_header_banner, null);
list.addHeaderView(headerView);

try {
     ImageView publicidadeView = (ImageView) headerView.findViewById(R.id.publicidadeView);
} catch (NullPointerException e) {
}

活动布局代码示例

<ListView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/lvResults"
    android:layout_gravity="center_horizontal|top"
    android:divider="@drawable/divider"
    /> 

【问题讨论】:

  • 我认为你的标题布局膨胀代码是错误的应该是:LayoutInflater.from(this).inflate(R.layout.list_header_banner, null);
  • 之前试过,错误变为“Error inflating class android.widget.AbsListView”

标签: android listview android-inflate


【解决方案1】:

尝试使用当前上下文 (this) 扩展布局:

View view = LayoutInflater.from(this).inflate(R.layout.list_header_banner, null);

【讨论】:

  • 之前试过,错误变为“Error inflating class android.widget.AbsListView”
【解决方案2】:

我刚刚尝试使用这个 sn-p,它对我有用。

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout headerLayout = (LinearLayout) inflater.inflate(R.layout.list_header_banner, null);
listView.addHeaderView(headerLayout);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多