Android - ClassCastException - 在从 LinearLayout 到 AbsListView 的 LayoutParams

标签 android android-listview

我有一个列表适配器,我正在尝试为 (item.xml) 设置自定义 xml 如果我不使用通货膨胀(通过应用程序上下文直接识别 TextView ),它可以完美地工作..但是我的 ListView 不能被主题化..

public View getView(int position, View convertView, ViewGroup parent) {
        //System.gc();
        TextView tv;

        LayoutInflater inflater = getLayoutInflater();

        View row = View.inflate(mContext,R.layout.item,null); //.inflate(R.layout.item, parent, false); doesnt work either..
        String id = null;
        if (convertView == null) {
            tv =  (TextView) row.findViewById(R.id.TextView01);;
        } else
            tv = (TextView) convertView;

[..]

logcat 我得到了这个..

    07-15 19:45:51.710: ERROR/AndroidRuntime(20185): FATAL EXCEPTION: main
        java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
        at android.widget.ListView.setupChild(ListView.java:1827)
        at android.widget.ListView.makeAndAddView(ListView.java:1794)
        at android.widget.ListView.fillDown(ListView.java:688)

我的 item.xml 文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_height="wrap_content"
          android:gravity="left|center"
          android:layout_width="fill_parent"
          android:paddingBottom="15px"
          android:background="#fff200"
          android:paddingTop="15px"
          android:paddingLeft="15px">

<TextView android:id="@+id/TextView01"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textSize="40px"
          android:textStyle="bold"
          android:layout_marginLeft="20px"
          android:textColor="#0099CC">
</TextView>
</LinearLayout>

最佳答案

问题是由于将您从适配器返回的控件包装在线性布局中引起的。从您的布局文件中丢失 LinearLayout(只需将 TextView 作为根),我认为它应该可以工作。

稍微扩展:您正在创建控件,然后将其添加到 LinearLayout。此时为其分配了一个 LinearLayout$LayoutParams 对象并将其设置为它的布局参数。然后你把它从线性布局中拉出来,放到你的 ListView 中,它不理解 LinearLayout$LayoutParams。

或者,从 getView 返回 row 而不是(正如我假设你现在正在做的那样,因为你已经从引用的代码中删除了返回行)返回 tv。

(另一个不相关的提示:您正在膨胀布局,然后在 convertView != null 时将其丢弃;这将导致慢速设备上的滚动性能不佳。仅在您确实需要时才执行膨胀。)

关于Android - ClassCastException - 在从 LinearLayout 到 AbsListView 的 LayoutParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11492678/

相关文章:

java - 如果我打开另一个 Activity ,如何使 Activity 在后台运行

android - 根据自定义适配器中的条件更改特定行的背景

android - 使用数据绑定(bind)时如何设置嵌套的回收器 View 适配器?

android - 如何将从网络下载的图像存储在缓存中?

Android 支持 v7 工具栏 setTitleTextAppearance 不工作

android - 首选项屏幕中 EditText 的输入类型?

android - Espresso 空闲资源不起作用

android - 如何在android中为不同屏幕尺寸的动画创建xml文件

带有空 TextView 的 Android SwipeRefreshLayout 无法正常工作

Viewpager Fragment 中的 Android Listview - 无滚动