如何用成员在kotlin中定义类可以在java派生类中访问

时间:2018-08-21 21:13:51

标签: inheritance kotlin kotlin-interop

在kotlin中定义了一个带有成员的类

@JvmField protected val clickHandler: BaseClickHandler
@JvmField protected var layoutId : Int

但是在Java中尝试扩展此类并访问成员时,会出错。

interface ViewDelegate {

    fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder
    fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: Data, position: Int)
}


open class ViewDelegateImp(@JvmField protected val clickHandler: BaseClickHandler) : ViewDelegate {

    @JvmField protected var layoutId = R.layout.default

    override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder {
        return ItemViewHolder(parent.inflate(layoutId, false), clickHandler)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: Data, position: Int) {
        (holder as? ItemViewHolder)?.bindView(item, position)
    }
}

//extension:
fun ViewGroup.inflate(layoutId: Int, attachToRoot: Boolean = false): View {
    return LayoutInflater.from(context).inflate(layoutId, this, attachToRoot)
}
Java中的

要从ViewDelegateImp派生,并覆盖var layoutId并使用受保护的val clickHandler

class DerivedDelegateImp extends ViewDelegateImp {

    public DerivedDelegateImp(BaseClickHandler clickHandler) {
        super(clickHandler);
        layoutId = R.layout.derived;  // want to use different layout, but get error "cannot resolve layoutId"
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, Data item, int position) {
        super.onBindViewHolder(holder, item, position);
    }

    @NotNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {

        View vw = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);

        return new StoryItemViewHolder(vw, clickHandler); // here got error clickHandler has private access in ViewDelegateImp 

        //return super.onCreateViewHolder(parent);  //<== this is fine
    }
}

1 个答案:

答案 0 :(得分:0)

这一定是IDE问题,无论其他什么(同步,清除,重建)都尝试过,它只有在删除项目并重新克隆以获取新的代码库并将这些代码重新添加后才起作用。