我有一段Java代码,我想更改为Kotlin语法。jave代码是:
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类的伴随对象的代码,因为我写了:
对象ViewHolder:RecyclewView.ViewHolder强制我提供((和View类型的参数到RecycleView.ViewHolder
我做不到
默认情况下,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...
}
}
您应该在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)