【问题标题】:How to Extend ListView如何扩展 ListView
【发布时间】:2014-11-25 20:33:04
【问题描述】:

感谢您的宝贵时间。

我已将ListView 扩展为:

public class PrettyListView extends ListView {

    public PrettyListView(Context context) {
        super(context);
    }

    public PrettyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PrettyListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
}

我在片段的上下文中并尝试像这样实例化它:

 listView = (PrettyListView) rootView.findViewById(R.id.list);

我收到以下错误:

 java.lang.ClassCastException: android.widget.ListView cannot be cast to com.sandbox.PrettyListView

请帮助我了解如何覆盖此错误,因为这是一个安全的演员表。

谢谢!

编辑:XML 按要求。再次感谢。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/wrapperView" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.sandbox.MainActivity$PlaceholderFragment">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true" />

</RelativeLayout>

【问题讨论】:

  • 问题出在你的 XML 文件中,也贴出来
  • 在带有 id 列表的片段视图布局中不是 PrettyListView 的实例
  • 阅读文档以获取自定义视图:developer.android.com/training/custom-views/index.html
  • 为什么这被否决了?这似乎是一个足够合理的问题。

标签: java android oop inheritance constructor


【解决方案1】:

错误是您的PrettyListViewListView,但ListView 不是您的PrettyListView。在您声明 ListView 的 xml 中,您必须声明您的 PrettListView:

   <com.sandbox.PrettyListView 
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/list" />

【讨论】:

  • 太棒了。感谢您关注 com.sandbox.* 前缀的细节。一个+!
【解决方案2】:

在您的 XML 文件中,您必须使用 PrettyListView 而不是 ListView

【讨论】:

  • 首先感谢您的回答。这里的问题是,虽然 com.sandbox.* 的包含对您来说可能很明显,但对我来说却不是,并且仍然引发了错误。祝你在 Android 中好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 1970-01-01
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
相关资源
最近更新 更多