当我将代码从Java转换为Kotlin时,我收到错误“Expecting member declaration”,为什么?

时间:2018-03-19 03:05:27

标签: android kotlin

当我将Java代码A复制到Android Studio 3.01中的Kotlin项目时,代码A会自动转换为代码B.

我通过Android Studio 3.01的提示在代码B中为override添加fun override onMenuItemClick(item: MenuItem)

但我仍然在代码B中得到错误的“期待成员声明”,我的kotlin Code B出了什么问题?

代码A

import android.support.v7.widget.PopupMenu;

 public static  void showPopup(View v, final Context mContext) {

        PopupMenu popup = new PopupMenu(mContext, v);
        popup.inflate(R.menu.menu_more);

        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                return HandleMenu(item, mContext);
            }
        });
        popup.show();
 }

代码B

import android.support.v7.widget.PopupMenu;

    fun showPopup(v: View, mContext: Context) {

        val popup = PopupMenu(mContext, v)
        popup.inflate(R.menu.menu_more)

        popup.setOnMenuItemClickListener(object : PopupMenu.OnMenuItemClickListener() {
            fun override onMenuItemClick(item: MenuItem): Boolean {
                return HandleMenu(item, mContext)
            }
        })

        popup.show()

    }

2 个答案:

答案 0 :(得分:2)

应该是override fun而不是fun override

此外,您可以使用Kotlin SAM并将其简化为popup.setOnMenuItemClickListener { item -> HandleMenu(item, mContext) },如IDE所示。

答案 1 :(得分:1)

你可以简单地替换它:

popup.setOnMenuItemClickListener(object : PopupMenu.OnMenuItemClickListener() {
            fun override onMenuItemClick(item: MenuItem): Boolean {
                return HandleMenu(item, mContext)
            }
        })

用这个:

popup.setOnMenuItemClickListener { item -> HandleMenu(item, mContext) }