2

我有一个 Java 代码,我想将其更改为 Kotlin 语法。java代码是:

  public class CountryDataItem (String countryNane,String countryUrl)
{
    public static RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent)
    {
        new ViewHolder (parent);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder
    {
        private TextView countryTextView;
        private ImageView countryImageView;
     
        public ViewHolder(@NonNull View view)
        {
            super(view);
            view.findViewById...
            ...
        }
    } 
}

代码与 RecyclerView 相关。我希望能够从静态嵌套类类型中创建尽可能多的 ViewHolder。我写了下面的代码,但感觉我像一个糟糕的代码,不可读(我不喜欢写匿名类,但不知道如何写“静态” ViewHolder 类并且总是返回相同的字段。

我写的代码:

   class CountryDataItem (val countryName :String, var countryFlagUrl )
{
    companion object
    {

         fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder {
             return object : RecyclerView.ViewHolder(parent) {
                 val countryNameTextView: TextView = parent.findViewById(R.id.country_name_tv)
                 val countryFlagUrl: ImageView = parent.findViewById(R.id.country_iv)
             }
         }
    }

我更喜欢使用扩展 RecyclerView.ViewHolder 类购买的伴随对象编写代码,因为编写:

object ViewHolder: RecyclewView.ViewHolder 强制我将View类型的提供()和参数提供给RecyclewView.ViewHolder

我做不到

4

2 回答 2

3

嵌套类在 Kotlin 中默认是静态的。您必须标记它们inner以使它们不是静态的。所以你的 Java 类在 Kotlin 中可能是这样的:

class CountryDataItem (val countryName: String, var countryFlagUrl: String) {

    companion object {
        fun onCreateViewHolder(parent: ViewGroup) = ViewHolder(parent)
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val countryTextView: TextView = view.findViewById...
        val countryImageView: ImageView = view.findViewById...
    } 
}
于 2020-11-10T17:26:07.887 回答
1

您应该在 ViewHolder 类中有伴生对象。像这样:

class CountryDataItem(countryName: String, countryUrl) {

    class ViewHolder private constructor(view: View): RecyclerView.ViewHolder(view) {
        private val textView: TextView = view.findViewById(R.id.textView)
        private val imageView: ImageView = view.findViewById(R.id.imageView)

        fun bind(model: Model) {
            textView.text = ...
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val layoutInflater = LayoutInflater.from(parent.context)
                val view = layoutInflater.inflate(R.layout.list_item, parent, false)
                
                return ViewHolder(view)
            }
        }
    }
}

现在要创建 ViewHolder,您只需调用该from方法即可。像这样:

CountryDataItem.ViewHolder.from(parent)
于 2020-11-10T17:32:22.497 回答