Kotlin版RecyclerView加item點選處理
阿新 • • 發佈:2019-02-18
之前個google定義kotlin為Android一級語言,小弟之前對kotlin也並不是很瞭解所以去了解之後寫了一份有關kotlin版的RecyclerView希望對新學習kotlin的人有一些幫助。
在使用kotlin之前我們要對在As中下載kotlin的外掛在重啟As之後新建一個Android專案在As的code欄最下面有一個convert Java file to kotlin file 轉換之後再Activity會有一個config的設定,它會幫你設定完kotlin在module的build.gradle和全域性build.gradle中設定kotlin的一系列配置
我們來看看我們的MainActivity頁面的操作
package com.example.liuqiang.kotlinforandroid import android.app.Activity import android.content.Context import android.os.Bundle import android.os.Handler import android.os.Message import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.View import android.widget.Button import android.widget.Toast import com.google.gson.* import com.google.gson.reflect.TypeToken import okhttp3.* import java.io.IOException class MainActivity : Activity() { //建立變數此處使用的網路訪問是基於okhttp的 var mOkHttpClient: OkHttpClient? = null var request: Request? = null; var body: FormBody? = null; var btn_back: Button? = null; val context: Context = this var recyclerView: RecyclerView? = null; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //載入資料 loadData() //初始化控制元件和繫結事件 btn_back = findViewById(R.id.btn_back) as Button; recyclerView = findViewById(R.id.recyclerView) as RecyclerView; btn_back!!.setOnClickListener { finish() } } fun loadData() { val path = "您的介面地址" //kotlin不需要new 可直接寫 mOkHttpClient = OkHttpClient() //對應引數 body = FormBody.Builder() .addEncoded("key", "val") .build() request = Request.Builder().url(path).post(body).build() //此處是重寫callback類也可以自己定義一個class類實現Callback mOkHttpClient!!.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call?, e: IOException?) { } override fun onResponse(call: Call?, response: Response?) { if (response != null) { if (response.isSuccessful) { //拿到伺服器返回引數 var response = response.body().string(); Log.d("###",response); try { //使用Gson解析返回資料 var gson: Gson = Gson() var json: JsonParser= JsonParser(); var jent: JsonElement=json.parse(response) as JsonElement; var job:JsonObject = jent.asJsonObject; var jar: JsonArray; jar = job.getAsJsonArray("rows"); //拿到gson類解析tyep val turnsType = object : TypeToken<ArrayList<TestInfo>>() {}.type val list: ArrayList<TestInfo>; //完成解析 list = gson.fromJson<ArrayList<TestInfo>>(jar, turnsType); //通知recyclerView var message = Message(); message.obj = list; hand.sendMessage(message); } catch(e: Exception) { println(e.message); } } } } }); } //完成recyclerView適配 var hand = object : Handler() { override fun handleMessage(msg: Message?) { super.handleMessage(msg) val list: ArrayList<TestInfo>; list = msg!!.obj as ArrayList<TestInfo> recyclerView!!.layoutManager = LinearLayoutManager(context); recyclerView!!.adapter = TestAdapter(list, context,itemClick()); } } //inner關鍵字可以方位外部類的引數 //次類是處理recyclerView的點選事件的 inner class itemClick: ItemClick{ override fun OnItemClick(v: View, position: Int) { Toast.makeText(context,"你點選了第"+(position+1)+"個",Toast.LENGTH_LONG).show(); } } }
在adapter裡面我們綁定了item點選介面的處理
package com.example.liuqiang.kotlinforandroid import android.content.Context import android.support.v7.widget.RecyclerView import android.support.v7.widget.RecyclerView.Adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import com.bumptech.glide.Glide import com.example.liuqiang.kotlinforandroid.TestAdapter.MyHolder import java.io.File class TestAdapter : Adapter<MyHolder> { //定義引數 var list: List<TestInfo>? = null; var contxt: Context? = null; //獲得事件回撥介面 var item:ItemClick?=null; //初始化資料 constructor(list: ArrayList<TestInfo>, contxt: Context,item:ItemClick) { this.list = list; this.contxt = contxt; this.item=item; } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyHolder { //得到itemView var v: View = LayoutInflater.from(contxt).inflate(R.layout.item, null, false); var holder = MyHolder(v); //為itemView繫結點選事件 v.setOnClickListener(onClick()); return holder; } override fun getItemCount(): Int { var size = list!!.size return size; } override fun onBindViewHolder(holder: MyHolder?, position: Int) { var name = list!!.get(position).username; holder!!.txtName.setText(name); var dept = list!!.get(position).deptname; var path = "您的圖片地址; if(path.contains(".jpg")||path.contains(".png")){ Glide.with(contxt) .load(path) .thumbnail(0.1f)//使用原圖的10/1作為略縮圖 .into(holder.image_head); }else{ holder.image_head.setImageResource(R.drawable.mv); } //得到position防止滑動點選錯位 holder.itemView.setTag(position); holder.bonus.setText(dept); } //viewHolder public class MyHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { var image_head: ImageView = itemView!!.findViewById(R.id.image_head) as ImageView; var txtName: TextView = itemView!!.findViewById(R.id.txtName) as TextView; var bonus: TextView = itemView!!.findViewById(R.id.bonus) as TextView; } //呼叫介面回撥 inner class onClick:View.OnClickListener{ override fun onClick(v: View?) { var positon:Int= v!!.getTag() as Int; if(item==null){ Toast.makeText(contxt,"哈哈哈",Toast.LENGTH_LONG).show(); } item!!.OnItemClick(v,positon); } } }
itemView點選處理介面
package com.example.liuqiang.kotlinforandroid
import android.view.View
/**
* Created by liuqiang on 2017/5/23.
*/
interface ItemClick {
fun OnItemClick(v: View,position:Int);
}
實體類
package com.example.liuqiang.kotlinforandroid
import java.io.Serializable
/**
* Created by liuqiang on 2017/5/21.
*/
//data 是資料類的關鍵字 預設給欄位配置get和set方法
data class TestInfo(var username:String, var fileContent:String,var deptname:String): Serializable{
}
最後的utils類
package com.example.liuqiang.kotlinforandroid
import android.app.ProgressDialog
import android.content.Context
/**
* Created by liuqiang on 2017/5/21.
*/
class Utils {
var dialog:ProgressDialog?=null;
fun showProgressDialog(context:Context,message:String,isFouse:Boolean){
if(dialog==null){
dialog=ProgressDialog(context);
}
dialog!!.setMessage(message);
dialog!!.setCancelable(isFouse);
dialog!!.setCanceledOnTouchOutside(isFouse);
dialog!!.show();
}
fun cancelProgressDialog(){
if(dialog!=null){
dialog!!.dismiss();
dialog=null;
}
}
}