android - 将类转换为Kotlin的子类

标签 android kotlin android-recyclerview android-architecture-components

我有一个名为“机会”的类的列表,其中填充了扩展“机会”的对象。该列表可以具有CommunityOpportunites或SponsorshipOpportunities。

我重写getItemViewType并根据相关位置中对象的子类为每个项目分配一个值,并对每个项目使用不同的ViewHolder:

override fun getItemViewType(position: Int): Int {

    return if (opportunityList[position] is SponsorshipOpportunity){

        Log.i(TAG,"Item type is sponsorshipId")

        SPONSORSHIP

    } else{
        Log.i(TAG,"Item type is community")
        COMMUNITY

    }

}

    inner class CommunityViewHolder(var view: CommunityTileBinding):RecyclerView.ViewHolder(view.root)
    inner class SponsorshipViewHolder(var view: SponsorshipTileBinding):RecyclerView.ViewHolder(view.root)



companion object{
    private const val COMMUNITY = 0
    private const val SPONSORSHIP = 1
}

在onCreateViewHolder()中,为项目的类创建正确的ViewHolder,在onBindViewHolder()中,我尝试将列表中的项目(在构造函数中为Opportunity类型)转换为 View 中项目的子类:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {


    val inflater = LayoutInflater.from(parent.context)

    return when (viewType){

        COMMUNITY->CommunityViewHolder(DataBindingUtil.inflate(inflater, R.layout.community_tile, parent, false))
        SPONSORSHIP-> SponsorshipViewHolder(DataBindingUtil.inflate(inflater, R.layout.sponsorship_tile, parent, false))

        else-> throw IllegalArgumentException()


    }
}

override fun getItemCount(): Int = opportunityList.size


override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

  when(holder.itemViewType){
      COMMUNITY-> {

          (holder as CommunityViewHolder).view.communityOpportunity = opportunityList[position] as CommunityOpportunity
      }
      SPONSORSHIP->{
          (holder as SponsorshipViewHolder).view.sponsorship = opportunityList[position] as SponsorshipOpportunity
          holder.view.postActionText.text = context.resources.getString(R.string.watch_respond)

      }
  }

}

但是,我得到以下类强制转换异常
java.lang.ClassCastException: com.example.model.Opportunity cannot be cast to com.example.model.CommunityOpportunity

当我尝试onBindViewHolder中的相关行时,即使打印了确认该项目是getItemViewType()中的CommunityOpportunity的日志语句。

有没有更好的方法问我,还是有更好的方法让我在RecyclerView中显示多个ViewHolder / Object类型?

编辑:这是相关的xml布局:


xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<data>
    <variable
        name="sponsorship"
        type="com.example.weare8sample.model.SponsorshipOpportunity"/>
</data>

<LinearLayout

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:elevation="2dp"
    android:orientation="vertical"
    android:background="@drawable/tile_background">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:foreground="@drawable/tile_background"
        android:imageUrl="@{sponsorship.coverTileUri}">

    </ImageView>



    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center_vertical"
        android:padding="10dp">

        <TextView
            android:id="@+id/postActionText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/lato_bold"
            tools:text="@string/watch_respond">

        </TextView>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:src="@drawable/ic_chevron_right_black_36dp">

        </ImageView>



    </RelativeLayout>

</LinearLayout>


xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<data>

    <variable
        name="communityOpportunity"
        type="com.example.weare8sample.model.CommunityOpportunity" />
</data>


<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="@drawable/tile_background"
    android:imageUrl="@{communityOpportunity.mediaImageUri}">

</ImageView>

最佳答案

getItemViewType中为所有类型添加显式类型检查,如果类型未知,则抛出该异常,以正确处理所有情况。

现在,如果存在第三种商机,则将其视为COMMUNITY类型。

关于android - 将类转换为Kotlin的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60936738/

相关文章:

Android:正确停止异步任务

android - openOptionsMenu 功能在 ICS 中不起作用?

android - 根据 Firestore 中的值,使用 if-else 语句更改 RecyclerView 中的 TextView

android - 中止 SAX 解析中间文档?

java - 为什么 Kotlin 接受声明为不可为空字符串的属性中的 null 值?

kotlin - CoroutineExceptionHandler 应该如何处理 OutOfMemoryError 或其他 fatal error ?

collections - 具有非空值的 Kotlin 映射

android - Recyclerview 在 onClick 方法上提供了错误的位置

android - RecyclerView - 网格布局管理器列的动画变化

android - Dagger 2 基于上下文的范围