我尝试在工具栏内创建一个自动完成的textview,但是当我从列表中加载数据时它不成功。我的代码: CountryAdapter
class CountryAdapter(
context: Context,resource: Int,textViewResourceId: Int,var items: List<CountryItem>) : ArrayAdapter<CountryItem>(context,resource,textViewResourceId,items) {
internal var tempItems: List<CountryItem> = ArrayList(items)
internal var suggestions: MutableList<CountryItem> = ArrayList()
/**
* Custom Filter implementation for custom suggestions we provide.
*/
private var nameFilter: Filter = object : Filter() {
override fun convertResultToString(resultvalue: Any): CharSequence {
return (resultvalue as CountryItem).countryName
}
override fun performFiltering(constraint: CharSequence?): FilterResults {
return if (constraint != null) {
suggestions.clear()
for (people in tempItems) {
if (people.countryName.toLowerCase().contains(constraint.toString().toLowerCase())) {
suggestions.add(people)
}
}
val filterResults = FilterResults()
filterResults.values = suggestions
filterResults.count = suggestions.size
filterResults
} else {
FilterResults()
}
}
override fun publishResults(constraint: CharSequence,results: FilterResults?) {
val filterList = results!!.values as ArrayList<CountryItem>
if (results.count > 0) {
clear()
for (people in filterList) {
add(people)
notifyDataSetChanged()
}
}
}
}
init {
// this makes the difference.
}
override fun getView(position: Int,convertView: View?,parent: ViewGroup): View {
var view = convertView
if (convertView == null) {
val inflater = context.getSystemService(Context.LAYOUT_INflaTER_SERVICE) as LayoutInflater
view = inflater.inflate(R.layout.country_autocomplete_row,parent,false)
}
val people = items[position]
val lblName = view!!.findViewById(R.id.text_view_name) as TextView
val img = view.findViewById(R.id.image_view_flag) as ImageView
lblName.text = people.countryName
img.setImageResource(people.flagImage)
return view
}
override fun getFilter(): Filter {
return nameFilter
}
}
主要活动
class Mainactivity : AppCompatactivity(),NavigationView.OnNavigationItemSelectedListener {
var countryList : List<CountryItem>?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportactionBar(toolbar)
fab.setOnClicklistener { view ->
snackbar.make(view,"Replace with your own action",snackbar.LENGTH_LONG)
.setaction("action",null).show()
}
val toggle = actionbardrawertoggle(
this,drawer_layout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close
)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
fillCountryList()
nav_view.setNavigationItemSelectedListener(this)
}
override fun onBackpressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackpressed()
}
}
private fun fillCountryList() {
countryList = mutableListOf(
CountryItem(1,"Afghanistan",R.drawable.afghanistan),CountryItem(2,"Bangladesh",R.drawable.bangladesh),CountryItem(3,"China",R.drawable.china),CountryItem(4,"India",R.drawable.india),CountryItem(5,"Japan",R.drawable.japan),CountryItem(6,"Nepal",R.drawable.nepal),CountryItem(7,"North Korea",R.drawable.nkorea),CountryItem(8,"South Korea",R.drawable.skorea),CountryItem(9,"Srilanka",R.drawable.srilanka),CountryItem(10,"Pakistan",R.drawable.pakistan)
)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main,menu)
// Get the search menu.
val searchMenu = menu.findItem(R.id.app_bar_menu_search)
// Get SearchView object.
val searchView = MenuItemCompat.getactionView(searchMenu) as SearchView
// Get SearchView autocomplete object.
val searchAutoComplete =
searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text) as SearchView.SearchAutoComplete
searchAutoComplete.setBackgroundColor(Color.BLUE)
searchAutoComplete.setTextColor(Color.GREEN)
searchAutoComplete.setDropDownBackgroundResource(android.R.color.holo_blue_light)
// Create a new ArrayAdapter and add data to search auto complete object.
val dataArr = arrayOf("Afghanistan","Pakistan")
// val newsAdapter = ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line,dataArr) val newsAdapter = CountryAdapter(this,R.layout.activity_main,R.id.text_view_name,countryList !!) searchAutoComplete.setadapter(newsAdapter)
// Listen to search view item on click event.
searchAutoComplete.onItemClicklistener =
AdapterView.OnItemClicklistener { adapterView,view,itemIndex,id ->
val queryString = adapterView.getItemAtPosition(itemIndex) as String
searchAutoComplete.setText("" + queryString)
Toast.makeText(this@Mainactivity,"you clicked $queryString",Toast.LENGTH_LONG).show()
}
// Below event is triggered when submit search query.
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
val alertDialog = AlertDialog.Builder(this@Mainactivity).create()
alertDialog.setMessage("Search keyword is $query")
alertDialog.show()
return false
}
override fun onQueryTextChange(newText: String): Boolean {
if (newText.isnotEmpty()){
return true
}
return false
}
})
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button,so long
// as you specify a parent activity in AndroidManifest.xml.
when (item.itemId) {
R.id.action_settings -> return true
R.id.app_bar_menu_search -> return true
else -> return super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.nav_camera -> {
// Handle the camera action
}
R.id.nav_gallery -> {
}
R.id.nav_slideshow -> {
}
R.id.nav_manage -> {
}
R.id.nav_share -> {
}
R.id.nav_send -> {
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
}
如果我使用数组字符串可以,但是当我使用列表时会给我错误
E / Android运行时:致命异常:主要 流程:com.robusta.autocompletesearchview,PID:16164 java.lang.IllegalArgumentException:指定为非null的参数为null:方法kotlin.jvm.internal.Intrinsics.checkParameterIsnotNull,参数约束 在com.robusta.autocompletesearchview.CountryAdapter $ nameFilter $ 1.publishResults(未知来源:24) 在android.widget.Filter $ ResultsHandler.handleMessage(Filter.java:282) 在android.os.Handler.dispatchMessage(Handler.java:106) 在android.os.Looper.loop(Looper.java:193) 在android.app.activityThread.main(activityThread.java:6669) 在java.lang.reflect.Method.invoke(本机方法) 在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:493) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)