Click on TextView open DialogFragment. Custom Listview set in DialogFragment. Listview item set in textview. Data set in Listview but when click listview item is not any response but when we click on listview item text then give error "java.lang.ClassCastException: java.lang.Integer cannot be cast model.Serve"
MainActivity.kt
binding.tvProductServeno.setOnClickListener {
var dialogC = CustomDialog(serveNo)
dialogC.show(supportFragmentManager,"customDialog")
}
CustomDialog.kt
class CustomDialog(val servList: ArrayList<Serve>) : DialogFragment() {
private val TAG = "CustomDialog"
interface OnInputListener {
fun sendInput(input: String?)
}
var mOnInputListener: OnInputListener? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val inflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val binding = DialogListViewBinding.inflate(inflater)
val builder = AlertDialog.Builder(requireContext())
val servAdapter = DialogListAdapter(servList, requireContext())
binding.listViewDialog.adapter = servAdapter
servAdapter.notifyDataSetChanged()
val dialog = builder.create()
dialog.show()
binding.listViewDialog.setOnItemClickListener { adapterView, view, i, l ->
val serve = adapterView.getItemAtPosition(i) as Serve
val serve1 = serve.serveNo
/* (activity as AddProduct?)..setText(input)*/
mOnInputListener?.sendInput(serve1.toString())
dialog.dismiss()
Toast.makeText(requireContext(), serve1.toString(), Toast.LENGTH_LONG).show()
}
return binding.root
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState)
}
override fun onAttach(context: Context) {
super.onAttach(context)
try {
mOnInputListener = activity as OnInputListener?
} catch (e: ClassCastException) {
Log.e(TAG, "onAttach: ClassCastException: " e.message)
}
}
}
Data Display in Listview. When Click on Listview item then it's not give any response. Listview iten value is not set in textview but click on listview item text is give error ClassCastException.
DialogListAdapter.kt
class DialogListAdapter (val servNo : ArrayList<Serve>,val context: Context) : BaseAdapter() {
override fun getCount(): Int {
return servNo.size
}
override fun getItem(p0: Int): Any {
return p0
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val binding = DialogListItemBinding.inflate(inflater)
//val serve = getItem(p0) as Serve
val ser = servNo.get(p0)
binding.tvListViewDialogItem.text = ser.serveNo
return binding.root
}
}
CodePudding user response:
Try to change the getItem
function in the DialogListAdapter
to:
override fun getItem(p0: Int): Serve = servNo[p0]