我必须使用Kotlin将ListView的单击项复制到剪贴板管理器。
我尝试过
listView.setOnItemClickListener { parent, view, position, id ->
val item = listView.selectedItem as String?
myClip = ClipData.newPlainText("text", item)
myClipboard?.primaryClip = myClip }
但是它说:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
我使用的ListView
var values = ArrayList<String>()
val adapter = ArrayAdapter(this, R.layout.listview_text_color, values)
listView?.adapter = adapter
adapter.notifyDataSetChanged()
答案 0 :(得分:1)
也许您的listview
为空。请改用listview?.setOnItemClickListener
答案 1 :(得分:0)
我没有使用listView布局,而是使用了alertDialog.setAdapter()。 这是代码
alertDialogList.setAdapter(adapter, DialogInterface.OnClickListener { _, which ->
val item = adapter.getItem(which) //this is my code to copy clicked items on clipboard
myClip = ClipData.newPlainText("text", item)
myClipboard?.primaryClip = myClip
})