没有为参数项传递值

时间:2017-07-25 17:19:44

标签: android android-studio kotlin

您好,我有这段代码:

override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_search, menu)
        val searchItem = menu.findItem(R.id.action_search)
        val searchView = MenuItemCompat.getActionView() as SearchView

        //*** setOnQueryTextFocusChangeListener ***
        searchView.setOnQueryTextFocusChangeListener(object : View.OnFocusChangeListener {

            override fun onFocusChange(v: View, hasFocus: Boolean) {

            }
        })

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {

            override fun onQueryTextSubmit(query: String): Boolean {

                return false
            }

            override fun onQueryTextChange(searchQuery: String): Boolean {
                adapter!!.filter(searchQuery.trim { it <= ' ' })
                tvListAnimal.invalidate()
                return true
            }
        })


        return true
    }

我在这一行中发现了一个错误:val searchView = MenuItemCompat.getActionView() as SearchView。实际上它只是代码的开头。事实上,Android Studio告诉我No value passed for parameter item,但我真的不知道我要放什么?

非常感谢您的帮助!真的!

编辑:这是menu_search.xml:

<?xml version="1.0" encoding="utf-8"?>


    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context=".SettingsFragment">
        <item android:id="@+id/action_search"
            android:title="Search"
            android:icon="@drawable/ic_search"
            app:showAsAction="collapseActionView|always"
            app:actionViewClass="android.support.v7.widget.SearchView"
            android:layout_width="wrap_content" />





</menu>

我在logcat中找到了这个:

 java.lang.ClassCastException: android.support.v7.widget.SearchView cannot be cast to android.widget.SearchView

1 个答案:

答案 0 :(得分:0)

问题是MenuItemCompat.getActionView()要求MenuItem作为参数传递:

val searchView = MenuItemCompat.getActionView(searchItem) as SearchView

如果您在使用的Android版本(as seen here)中将其删除,则应使用此版本:

val searchView = searchItem.getActionView() as SearchView