SoI'm learning kotlin and now I need to write an ArrayAdapter, but I've some error when trying to do this:
convertView = vi.inflate(resource, null)
kotlin is telling me
Val cannot be reassigned
In the site kotline I convert java class to kotlin class and try to do like in this site. Why is there an error and how can I fix this? Here is the whole code.
open class MyAdapter(context: Context, resource: Int, list: ArrayList<MyItems>) : ArrayAdapter<MyItems>(context, resource, list) { var resource: Int var list: ArrayList<MyItems> var vi: LayoutInflater init { this.resource = resource this.list = list this.vi = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? { var holder: ViewHolder if(convertView == null){ convertView = vi.inflate(resource, null) //error in this line holder = ViewHolder() holder.image = convertView.findViewById(R.id.myImage) as ImageView? convertView.tag(holder) //error in this line } else { holder = convertView.tag as ViewHolder } return convertView } internal class ViewHolder { var image: ImageView? = null } }
android.widget.ArrayAdapter. You can use this adapter to provide views for an AdapterView , Returns a view for each object in a collection of data objects you provide, and can be used with list-based user interface widgets such as ListView or Spinner .
Go to app > res > layout > right-click > New > Layout Resource File and create a new layout file and name this file as item_view. xml and make the root element as a LinearLayout. This will contain a TextView that is used to display the array objects as output.
Parameter variable cannot be re-assigned, you will need to create a local variable to hold your returned view:
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? { var holder: ViewHolder var retView: View if(convertView == null){ retView = vi.inflate(resource, null) holder = ViewHolder() holder.image = retView.findViewById(R.id.myImage) as ImageView? retView.tag = holder } else { holder = convertView.tag as ViewHolder retView = convertView } return retView }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With