Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayAdapter use Kotlin android

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     }  } 
like image 395
g71132 Avatar asked Jan 29 '17 17:01

g71132


People also ask

What is ArrayAdapter in Kotlin?

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 .

How do I use ArrayAdapter?

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.


1 Answers

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 } 
like image 90
Kiskae Avatar answered Sep 25 '22 06:09

Kiskae