首页 > 解决方案 > 为什么 BaseAdapter 不需要括号?

问题描述

我在问为什么我不能写这个:

class myClass : BaseAdapter() {
        }

而不是这个:

class myClass : BaseAdapter {
        }

BaseAdapter 是一个接口。

标签: androidandroid-layoutkotlin

解决方案


BaseAdapter是一个abstract类,而不是一个interface. 在 Kotlin 中,如果你从一个类(abstract或其他)扩展,你需要使用构造函数调用。

如果你从这个开始:

import android.widget.BaseAdapter

class myClass : BaseAdapter() {

}

...你会得到一个错误:

Android Studio,显示错误

那是因为您缺少abstract课程所需的功能。如果您将文本光标放在class myClass错误区域并按Alt-Enter,您可以选择“实现方法”,选择所有四个方法,Android Studio 将为TODO()您生成这些方法的实现代码:

import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter

class myClass : BaseAdapter() {
  override fun getView(
    position: Int,
    convertView: View?,
    parent: ViewGroup?
  ): View {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
  }

  override fun getItem(position: Int): Any {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
  }

  override fun getItemId(position: Int): Long {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
  }

  override fun getCount(): Int {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
  }

}

此时,您应该没有更多错误。


推荐阅读