Android Kotlin

Kotlin

    • Kotlin

Kotlin

kotlin 的基本用法:
创建类的时候把下面java选成kotlin这样就可以用kotlin
kotlin获取控件:import kotlinx.android.synthetic.main.主布局名.*
kotlin声明变量:var 名字:类型
kotlin声明类: class 类名(var 名字:类型,var 名字:类型):继承的类{
}
kotlin声明类部类:inner class 类名(var 名字:类型,var 名字:类型):继承的类{
}
kotlin声明方法:fun 方法名(var 名字:类型,var 名字:类型):返回值类型{
}

kotlin中的handler:

// An highlighted block
  handler=object :Handler(){
             override fun handleMessage(msg: Message?) {
                 super.handleMessage(msg)
                 when(msg!!.what){
                     100->{
                        list = msg.obj as ArrayList<Bean>
                         val myAdapter = MyAdapter(this@Main2Activity, list)
                         main2_list.adapter=myAdapter
                     }
                 }
             }
         }

kotlin中的listview适配器

// An highlighted block
class MyAdapter(var context:Context,var list:ArrayList<Bean>): BaseAdapter() {



    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
       var viewHolder:ViewHolder?=null
        var view :View?=null
        if(convertView==null){
            view= View.inflate(context, R.layout.listview,null)
            viewHolder=ViewHolder()
            viewHolder.text1=view.findViewById(R.id.list_text1)
            viewHolder.text2=view.findViewById(R.id.list_text2)
            viewHolder.img=view.findViewById(R.id.list_img)
            view.tag=viewHolder
        }else{
           view=convertView
            viewHolder=view.tag as ViewHolder

        }

            viewHolder.text1?.text = list[position].title
            viewHolder.text2?.text = list[position].food
            Glide.with(context).load(list[position].pic).into(viewHolder.img)

        return view!!
    }

    inner class ViewHolder{
        var text1:TextView?=null
        var text2:TextView?=null
        var img:ImageView?=null
    }

    override fun getItem(position: Int): Any {
        return position
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount(): Int {
        return list.size
    }
}

kotlin中的类

// An highlighted block
class Bean(var title:String,var food:String,var pic:String) {
    override fun toString(): String {
        return title+"---"+food+"---"+pic
    }
}

kotlin中方法

// An highlighted block
fun getjson():ArrayList<Bean>{
      return list
}

你可能感兴趣的:(Android Kotlin)