Android開(kāi)發(fā)-kotlin基本使用(一)

1榜贴、RecyclerView列表布局

在item_view_linear_vertical.xml中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:orientation="vertical"
    android:layout_height="80dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:layout_height="0dp">

        <ImageView
            android:id="@+id/item_image"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center_vertical"
            android:src="@drawable/ic_launcher_foreground"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/item_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="地東段減肥標(biāo)題課程"
                android:textColor="#000000"
                android:textStyle="bold"
                android:singleLine="true"
                android:maxLines="10"
                android:ellipsize="end"
                android:textSize="18dp"/>

            <TextView
                android:id="@+id/item_message"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="6dp"
                android:text="內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容內(nèi)容呢絨內(nèi)容"
                android:textColor="#666666"
                android:textStyle="normal"
                android:singleLine="true"
                android:ellipsize="end"
                android:textSize="14dp"/>
        </LinearLayout>
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#f3f3f3"/>
</LinearLayout>
在fragment_study.xml中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ui.study.StudyFragment">

    <TextView
        android:id="@+id/text_home"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:gravity="center"
        android:background="@color/purple_700"
        android:textAlignment="center"
        android:textSize="20sp"
        android:text="LinerLayoutManager列表布局"
        android:textColor="@color/white" />

    <!--    要使用RecyclerView, 首先要確保項(xiàng)目&ndash;&gt;app&ndash;&gt;build.gradle里面
    dependencies {
        implementation 'androidx.recyclerview:recyclerview:1.0.2'
        ...
    }
    -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <!--    <androidx.recyclerview.widget.RecyclerView/>-->

</LinearLayout>
在ui-->study-->StudyFragment中:
package com.dbc.bckotlinall.ui.study

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.dbc.bckotlinall.R
import kotlinx.android.synthetic.main.fragment_study.*
import kotlinx.android.synthetic.main.item_view_linear_vertical.view.*


class StudyFragment: Fragment(R.layout.fragment_study) {//關(guān)聯(lián)布局
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 需要先安裝擴(kuò)展插件, 就可以直接通過(guò)id名訪問(wèn)控件了
        recycler_view.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
        recycler_view.adapter = StudyAdapter()
    }

    // inner 用于聲明StudyAdapter是StudyFragment的內(nèi)部類(lèi)
    inner class StudyAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val itemView = LayoutInflater.from(context).inflate(R.layout.item_view_linear_vertical, parent, false)
            return StudyViewHolder(itemView)
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
          
            /// 在代碼中給image控件設(shè)置圖片的三種方式:
            holder.itemView.item_image.setImageResource(R.drawable.ic_dashboard_black_24dp)//?
            holder.itemView.item_image.setImageDrawable(
              ContextCompat.getDrawable(
                context!!,// !!表示說(shuō)明此對(duì)象不為空
                R.drawable.icon_jetpack
              )
            )
            holder.itemView.item_image.setImageBitmap(BitmapFactory.decodeResource(context!!.resource, R.drawable.icon_jetpack))
          
            holder.itemView.item_title.text="標(biāo)題$position"
            holder.itemView.item_message.text="內(nèi)容${position} 能接收到分離焦慮世紀(jì)東方垃圾水電費(fèi)拉伸點(diǎn)擊分類(lèi)計(jì)數(shù)法  打開(kāi)了施法距離卡機(jī)士大夫撒的發(fā)生撒旦法阿斯頓發(fā)安達(dá)市 發(fā)"
        }

        override fun getItemCount(): Int {
            return 20
        }

        inner class StudyViewHolder(view: View):RecyclerView.ViewHolder(view){

        }

    }
}

2、GradLayoutManager網(wǎng)格布局

class HomeFragment : Fragment(R.layout.fragment_home){
  override fun onViewCreated(view: View, savedInstanceState: Bundle?){
    super.onViewCreated(View, savedInstanceState)
    
    recycler_view.layoutManager = LinearLayoutManager(context, 3)//3表示3列
    
    recycler_view.adapter = MyAdapter()
  }
  
  // inner: 聲明MyAdapter為HomeFragment的內(nèi)部類(lèi)
  inner class MyAdapter: RecyclerView.Adapter<MyViewHolder>(){
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyVIewHolder{
      //訪問(wèn)外部類(lèi)的context對(duì)象
      val itemView = LayoutInflater.from(context)
        .inflate(R.layout.item_view_grid, parent, false)
      return MyViewHolder(itemView)
    }
    
    // 告訴列表有多少條數(shù)據(jù)
    override fun getItemCount(): Int{
      return 20
    }
    
    //數(shù)據(jù)綁定
    override fun onBindViewHolder(holder: MyViewHolder, position: Int){
      /// 在代碼中給image控件設(shè)置圖片的三種方式:
      holder.itemView.item_image.setImageResource(R.drawable.icon_jetpack)//?
      holder.itemView.item_image.setImageDrawable(
        ContextCompat.getDrawable(
          context!!,// !!表示說(shuō)明此對(duì)象不為空
          R.drawable.icon_jetpack
        )
      )
      holder.itemView.item_image.setImageBitmap(BitmapFactory.decodeResource(context!!.resource, R.drawable.icon_jetpack))
    }
  }
  
  class MyViewHolder(view: View): RecyclerView.ViewHolder(view){
    
  }
}

3畸裳、StaggeredGridLayoutManager瀑布流


recycleView.adapter = MyAdapter()

class HomeFragment : Fragment(R.layout.fragment_home){
  override fun onViewCreated(view: View, savedInstanceState: Bundle?){
    super.onViewCreated(View, savedInstanceState)
    
    recycler_view.layoutManager = StaggeredGridLayoutMananger(2, StaggeredGridLayoutMananger.VERTICAL)//2表示2列, VERTICAL表示縱向瀑布流
    
    recycler_view.adapter = MyAdapter()
  }
  
  // inner: 聲明MyAdapter為HomeFragment的內(nèi)部類(lèi)
  inner class MyAdapter: RecyclerView.Adapter<MyViewHolder>(){
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyVIewHolder{
      //訪問(wèn)外部類(lèi)的context對(duì)象
      val itemView = LayoutInflater.from(context)
        .inflate(R.layout.item_view_grid, parent, false)
      return MyViewHolder(itemView)
    }
    
    // 告訴列表有多少條數(shù)據(jù)
    override fun getItemCount(): Int{
      return 20
    }
    
    //數(shù)據(jù)綁定
    override fun onBindViewHolder(holder: MyViewHolder, position: Int){
      /// 在代碼中給image控件設(shè)置圖片的三種方式:
      holder.itemView.item_image.setImageResource(R.drawable.icon_jetpack)//?
      if(position == 0||position == 3||position == 4||position == 7||position == 9){
        holder.itemView.item_message.setSingleLine(false)//取消設(shè)置單行顯示
      } else {
        holder.itemView.item_message.setSingleLine(true)//單行顯示
      }
      holder.itemView.item_message.text = "xxxxx"
    }
  }
  
  class MyViewHolder(view: View): RecyclerView.ViewHolder(view){
    
  }
}

4仿吞、快速實(shí)現(xiàn)圓角陰影的組件

// 這一行代碼, 放在頂部layout標(biāo)簽中聲明
xmlns:app="http://schemas.android.com/apk/res-auto"

<androidx.cardview.widget.CardView
    android: layout_width = "match_parent"
    app:cardBackgroundColor="@color/white"http://設(shè)置背景色
    app:CardCornerRadius="10dp"http://設(shè)置圓角
    Android: layout_marginLeft="16dp"
    Android: layout_marginRight="16dp"
    android: layout_height="140dp">
    <LinerLayout
      android:layout_width="match_parent"
      androdi:layout_height="match_parent"
      android:orientation="horizontal">
        <com.google.android.material.button.MaterialButton
                    android:id="@+id/item_collect"
          android: layout_width="0dp"
                    style="@style/Widget.MaterialComponents.Button.UnelevatedButton"http://去除按鈕默認(rèn)描邊陰影效果
          androdi:layout_height="match_parent"
          android:layout_weight="1"
          android:backgroundTint="@color/white"
          android:text="收藏"
          app:icon="@drawable/main_component_my_course_collect"
          app:iconGravity="textTop"http://icon位于文字的上方
                    app:iconSize="25dp"
                    app:iconTint="@null"http://icon默認(rèn)顏色為白色, 設(shè)置為空顯示原有顏色
                    android:padding="0dp"http://去除默認(rèn)內(nèi)間距
                    android:insetTop="0dp"http://去除默認(rèn)留白
                    android:insetBottom="0dp"http://去除默認(rèn)留白
          android:textColor="#333333"/>
        ...
  </LinerLayout>             
</androidx.cardview.widget.CardView>
AndroidStudio配置阿里云鏡像  2021.02.25 10:46 2020瀏覽
https://www.imooc.com/article/315290


Mac IDEA配置阿里云國(guó)內(nèi)鏡像 發(fā)布于 2020-07-30
https://segmentfault.com/a/1190000023086534


警告:You have JVM property “https.proxyHost“ set to “127.0.0.1“
http://www.reibang.com/p/9cec82d9498e

5滑频、網(wǎng)絡(luò)請(qǐng)求框架OKHTTP--GET請(qǐng)求

在app->manifests->AndroidManifest.xml添加網(wǎng)絡(luò)訪問(wèn)權(quán)限:

<!--    請(qǐng)求權(quán)限-->
    <uses-permission android:name="android.permission.INTERNET" />
<!--    寫(xiě)入權(quán)限-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--    讀取權(quán)限-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
             ...
             android:usesCleartextTraffic="true" //允許發(fā)起Http請(qǐng)求
             ....>
</application>

app/build.gradledependencies中添加下面的依賴(lài)

dependencies {
  ...
  implementation("com.squareup.okhttp3:okhttp:4.9.0")
  // 網(wǎng)絡(luò)請(qǐng)求日志打印
  implementation("com.squareup.okhttp3:logging-interceptor:4.9.0")
}

在http->HiOkHttp中

package com.dbc.bckotlinall.http

import android.util.Log
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.Request
import java.util.concurrent.TimeUnit

// 使用class需要?jiǎng)?chuàng)建實(shí)例對(duì)象
// 使用object的聲明方式, 就沒(méi)有必要構(gòu)建它的實(shí)例對(duì)象了, 直接可以類(lèi).方法調(diào)用
object HiOkHttp {
    private val BASE_URL="http://123.56.232.18:8080/serverdemo"
    //全局中只有一份
    val client  = OkHttpClient.Builder()    //builder構(gòu)造者設(shè)計(jì)模式
        .connectTimeout(10, TimeUnit.SECONDS) //連接超時(shí)時(shí)間
        .readTimeout(10, TimeUnit.SECONDS)    //讀取超時(shí)
        .writeTimeout(10, TimeUnit.SECONDS)  //寫(xiě)超時(shí),也就是請(qǐng)求超時(shí)
        .build();

    // Android分為主線程和子線程
    // 主線程就是APP一啟動(dòng)后, Android framework層會(huì)啟動(dòng)一個(gè)線程, 主線程(UI線程)
    // 子線程 -- 可以通過(guò)new Thread().start()創(chuàng)建

    //方式一: 同步GET請(qǐng)求
    fun get(url: String) {//網(wǎng)絡(luò)請(qǐng)求接口
        Thread(Runnable {//開(kāi)啟子線程
            //構(gòu)造請(qǐng)求體
            val request: Request = Request.Builder()
//                .url(url)
                .url("$BASE_URL/user/query?userId=1600932269")
                .build()
            //構(gòu)造請(qǐng)求對(duì)象
            val call: Call = client.newCall(request)
            // 通過(guò).execute()發(fā)起同步請(qǐng)求--同步執(zhí)行
            val response = call.execute()
            val body = response.body?.string()
//            println("get response :${body}")
            Log.e("OKHTTP","get response :${body}")
        }).start()
    }
  
  //方式二: 異步GET請(qǐng)求
  fun getAsync(url: String) {//網(wǎng)絡(luò)請(qǐng)求接口
        //構(gòu)造請(qǐng)求體
        val request: Request = Request.Builder()
//                .url(url)
            .url("$BASE_URL/user/query?userId=1600932269")
            .build()
        //構(gòu)造請(qǐng)求對(duì)象
        val call: Call = client.newCall(request)
        // 通過(guò).enqueue()發(fā)起異步請(qǐng)求--異步執(zhí)行
        call.enqueue(object: Callback {//異步請(qǐng)求沒(méi)有返回值
            override fun onFailure(call: Call, e: IOException) {
                Log.e("OKHTTP","失敗原因 :${e}")
            }

            override fun onResponse(call: Call, response: Response) {
                val body = response.body?.string()
                Log.e("OKHTTP","get response :${body}")
            }
        })
    }
}

在MainActivity.kt中使用:

HiOkHttp.get()

6唤冈、網(wǎng)絡(luò)請(qǐng)求框架OKHTTP--POST請(qǐng)求

http://123.56.232.18:8080/serverdemo/swagger-ui.html#/tag-list-controller/toggleTagFollowUsingPOST

/// 同步表達(dá)提交
fun post(){
    val body = FormBody.Builder()
        .add("userId","1600932269")
        .add("tagId","71")
        .build()
    val request = Request.Builder().url("$BASE_URL/tag/toggleTagFollow")
        .post(body)
        .build()
    val call = client.newCall(request)
    Thread(Runnable {
        val response = call.execute()
        Log.e("OKHTTP","post response: ${response.body?.string()}")
    }).start()
}

/// 異步表單提交
fun postAsync(){
    val body = FormBody.Builder()
        .add("userId","1600932269")
        .add("tagId","71")
        .build()
    val request = Request.Builder().url("$BASE_URL/tag/toggleTagFollow")
        .post(body)
        .build()
    val call = client.newCall(request)
    call.enqueue(object :Callback{
        override fun onFailure(call: Call, e: IOException) {
            Log.e("OKHTTP","失敗原因 :${e}")
        }

        override fun onResponse(call: Call, response: Response) {
            val body = response.body?.string()
            Log.e("OKHTTP","post response :${body}")
        }
    })
}

/// 異步多表單文件上傳, 在Android6.0以后, 讀取外部存儲(chǔ)卡文件都是需要?jiǎng)討B(tài)申請(qǐng)權(quán)限的
fun postAsyncMultipart(context: Context) {

    val file = File(Environment.getExternalStorageDirectory(), "1.png")// 文件目錄, 文件名稱(chēng)
    if (!file.exists()) {
        Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show()
        return
    }
    val body = MultipartBody.Builder()
        .addFormDataPart("key","value")
        .addFormDataPart("key1","value1")
        .addFormDataPart(
            "file",
            "1.png",
            RequestBody.create("application/octet-stream".toMediaType(), file)
        )
        .build()

    val request = Request.Builder().url("接口是需要支持文件上傳才可以使用的")
        .post(body)
        .build()

    val  call = client.newCall(request)
    call.enqueue( object : Callback{
        override fun onFailure(call: Call, e: IOException) {
            Log.e("OKHTTP","失敗原因 :${e}")
        }

        override fun onResponse(call: Call, response: Response) {
            val body = response.body?.string()
            Log.e("OKHTTP","postAsyncMultipart response :${body}")
        }
    })
}

/// 異步POST請(qǐng)求---提交字符串
fun postString(){
    ///可以是JSON字符串, 也可以是純文本字符串

    //純文本
//        val textPlain = "text/plain;charset=utf-8".toMediaType()
//        val textObj = "{username:admin, password:admin}"
//        val body = RequestBody.create(textPlain,textObj)

    //Json字符串
    val jsonObj = JSONObject()
    jsonObj.put("key1","value1")
    jsonObj.put("key2",100)
    val applicationJson = "application/json;charset=utf-8".toMediaType()

    val body = RequestBody.create(applicationJson,jsonObj.toString())

    val request = Request.Builder().url("$BASE_URL")
        .post(body)
        .build()

    val  call = client.newCall(request)
    call.enqueue( object : Callback{
        override fun onFailure(call: Call, e: IOException) {
            Log.e("OKHTTP","失敗原因 :${e}")
        }

        override fun onResponse(call: Call, response: Response) {
            val body = response.body?.string()
            Log.e("OKHTTP","postString response :${body}")
        }
    })
}

7峡迷、攔截器LoggingInterceptor

使用OkHttp默認(rèn)攔截器
object HiOkHttp {
    private val BASE_URL="http://123.56.232.18:8080/serverdemo"
    private  val client: OkHttpClient 

    init {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        client  = OkHttpClient.Builder()    //builder構(gòu)造者設(shè)計(jì)模式
            .connectTimeout(10, TimeUnit.SECONDS) //連接超時(shí)時(shí)間
            .readTimeout(10, TimeUnit.SECONDS)    //讀取超時(shí)
            .writeTimeout(10, TimeUnit.SECONDS)  //寫(xiě)超時(shí),也就是請(qǐng)求超時(shí)
            .addInterceptor(httpLoggingInterceptor)//使用默認(rèn)攔截器
            .build();
    }
    ....
}
使用自定義攔截器:
/// ①在LoggingInterceptor.kt中:

package com.dbc.bckotlinall.http

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer

/// 攔截器要做的事: 打印攔截請(qǐng)求時(shí)的接口你虹、攜帶哪些參數(shù)
class LoggingInterceptor: Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val time_start = System.nanoTime()
        val request = chain.request() //獲取request對(duì)象
        val response = chain.proceed(request)//獲取response對(duì)象

        val buffer = Buffer()
        request.body?.writeTo(buffer)
        val requestBodyStr = buffer.readUtf8()//把request.body轉(zhuǎn)換成字符串
        //打印請(qǐng)求前的: 地址 和 請(qǐng)求參數(shù)
        Log.e("OKHTTP",String.format("Sending request %s with params %s",request.url, requestBodyStr))

        val bussinessData = response.body?.string()?:"response body null" //讀取輸出流,獲取接口返回的數(shù)據(jù)
        /*由于OKHTTP的工作原理: 一旦調(diào)用了response.body?.string()方法, 今后再也不能用response去讀取它的響應(yīng)流了.
        *
        * 這也就意味著: onResponse回調(diào)函數(shù)中,再次讀取response.body?.string()就會(huì)報(bào)錯(cuò). 這是OKHTTP的工作原理決定的.
        *
        * 對(duì)于Response響應(yīng)流只能讀取一次的解決辦法是: 返回一個(gè)新的Response.
        * */
        val mediaType = response.body?.contentType()
        val newBody = ResponseBody.create(mediaType, bussinessData)
        val newResponse = response.newBuilder().body(newBody).build()

        val time_end = System.nanoTime()
        //打印請(qǐng)求后的結(jié)果
        Log.e("OKHTTP", String.format("Received response for %s in %.1fms >>> %s", request.url,(time_end-time_start)/1e6,bussinessData))

        return newResponse
    }
}

///②在HiOkHttp中使用:
object HiOkHttp {
    private val BASE_URL="http://123.56.232.18:8080/serverdemo"

    val client  = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)  
        .addInterceptor(LoggingInterceptor()) //添加自定義攔截器
        .build();
    ...
}

8绘搞、使用Gson來(lái)解析網(wǎng)絡(luò)請(qǐng)求響應(yīng)

app/build.gradle中添加以下依賴(lài)配置

dependencies {
  implementation 'com.google.code.gson:gson:2.8.6'
}

在Account.kt中使用:

package com.dbc.bckotlinall.ui.study

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

fun main() {

    /// 把JSON轉(zhuǎn)換成對(duì)象
    val json ="{\"uid\":\"00001\",\"userName\":\"Freeman\",\"telNumber\":\"13000000000\"}"
    val gson = Gson()//構(gòu)建gson對(duì)象
    // 在kotlin中傳入class類(lèi)型, 需要xxx::class.java 格式
    val account:Account = gson.fromJson<Account>(json, Account::class.java)
    println("fromJson: ${account.toString()}")

    /// 把對(duì)象轉(zhuǎn)換成JSON
    val accountJson = gson.toJson(account)
    println("toJson: ${accountJson}")

    /// 將JSON轉(zhuǎn)換成集合
    val jsonList= "[{\"uid\":\"00001\",\"userName\":\"Freeman\",\"telNumber\":\"13000000000\"}]"
    val accountList: List<Account> = gson.fromJson(jsonList, object:TypeToken<List<Account>>(){}.type)
    println("fromJson to List:${accountList.size}")

    /// 將集合轉(zhuǎn)化成JSON
    val accountJsonList = gson.toJson(accountList)
    println("list to json: ${accountJsonList}")
}

class Account {
    /// 在kotlin中必須指定初始值
    var uid:String=""
    var userName:String=""
    var password:String=""
    var telNumber:String=""

    //?快速生成toString: 首先選中這幾個(gè)字段-->右鍵"Generate"-->選擇"toString()"-->全選
    override fun toString(): String {
        return "Account(uid='$uid', userName='$userName', password='$password', telNumber='$telNumber')"
    }
}

如果對(duì)象模型使用data class, 就可以不用指定初始值了:

data class Account(
    var uid:String = "111",
    var userName:String,
    var password:String,
    var telNumber:String
)

使用插件快速生成復(fù)雜的數(shù)據(jù)模型 -- JsonToKotlin插件:

sp1.在網(wǎng)站 https://github.com/wuseal/JsonToKotlinClass/releases/  下載最新版本zip包
sp2.在AS-->Preferences-->Plugins-->點(diǎn)擊"設(shè)置"按鈕, 選擇"install Plugin from Disk..."--->選擇下載的包,點(diǎn)擊"OK", 重啟IDE

使用插件:
在空白的地方, 右鍵選擇"Generate"-->選擇"Kotlin data classes from JSON"-->將JSON字符串拷貝到這里-->點(diǎn)擊"Format", 輸入"Class Name: xxx", 選擇"Generate" --> 就生成了xxx對(duì)象模型

val userModelJson = "{ ... }"
val userResponse:UserResponse! =  gson.fromJson<UserResponse>(userModelJson, UserResponse::class.java)
println("userResponse: $userResponse")

9、RESTFUL網(wǎng)絡(luò)請(qǐng)求框架Retrofit

retrofit注解驅(qū)動(dòng)型上層網(wǎng)絡(luò)請(qǐng)求框架, 使用注解來(lái)簡(jiǎn)化請(qǐng)求, 大體分為以下幾類(lèi):

  • 用于標(biāo)注網(wǎng)絡(luò)請(qǐng)求的注解
  • 標(biāo)記網(wǎng)絡(luò)請(qǐng)求參數(shù)的注解
  • 用于標(biāo)記網(wǎng)絡(luò)請(qǐng)求和響應(yīng)格式的注解
添加依賴(lài):
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0' //json轉(zhuǎn)換
在HiRetrofit.kt中, 封裝Retrofit&定義接口:
package com.dbc.bckotlinall.http

import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import java.util.concurrent.TimeUnit

object HiRetrofit {

    // https://www.cnblogs.com/hanma/p/14942740.html

    private val client  = OkHttpClient.Builder()    //builder構(gòu)造者設(shè)計(jì)模式
        .connectTimeout(10, TimeUnit.SECONDS) //連接超時(shí)時(shí)間
        .readTimeout(10, TimeUnit.SECONDS)    //讀取超時(shí)
        .writeTimeout(10, TimeUnit.SECONDS)  //寫(xiě)超時(shí)傅物,也就是請(qǐng)求超時(shí)
        .addInterceptor(LoggingInterceptor())
        .build();

    private val retrofit = Retrofit.Builder()
        .client(client)//配置OKHTTP網(wǎng)絡(luò)請(qǐng)求的一個(gè)對(duì)象
        .baseUrl("http://123.56.232.18:8080/serverdemo/")//配置網(wǎng)絡(luò)請(qǐng)求的域名
        .addConverterFactory(GsonConverterFactory.create())//數(shù)據(jù)轉(zhuǎn)換器: 自動(dòng)轉(zhuǎn)換成數(shù)據(jù)模型
        .build();

    ///定義一個(gè)泛型方法
    fun <T> create(clazz: Class<T>): T {
        return retrofit.create(clazz)
    }
}

/// 定義一個(gè)接口文件, 編寫(xiě)網(wǎng)絡(luò)請(qǐng)求方法
interface APIService{
    @GET(value="user/query")
    fun queryUser(@Query(value="userId",encoded = true) userId: String):Call<UserResponse>
  //UserResponse: 要轉(zhuǎn)換的數(shù)據(jù)模型對(duì)象類(lèi)
}

在MainActivity.kt中使用:

val apiService = HiRetrofit.create(APIService::class.java)
// 此時(shí)onFailure 和 onResponse的回調(diào)都是在主線程的; 但OKHTTP的回調(diào)是在子線程的,如果UI操作還需要回到主線程.
apiService.queryUser("1600932269").enqueue(object: Callback<UserResponse>{
    override fun onFailure(call: Call<UserResponse>, t: Throwable) {
        Log.e("Retrofit","失敗原因 :${t.message}")
    }

    override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
        val body = response.body?.string()
        Log.e("Retrofit","get response :${body}")
    }
})

10夯辖、網(wǎng)絡(luò)圖片的加載

在app/build.gradle中添加以下配置。使用Glide加載圖片

plugins {
    ...
    id 'kotlin-kapt'
}

dependencies {
    ...
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    kapt 'com.github.bumptech.glide:compiler:4.9.0'
}

11董饰、數(shù)據(jù)請(qǐng)求與綁定

class StudyFragment: Fragment(R.layout.fragment_study) {//關(guān)聯(lián)布局
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = StudyAdapter()
        recycler_view.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
        recycler_view.adapter = adapter
      
        HiRetrofit.create(ApiService::class.java)
            .getStudy().enqueue(object: CallBack<List<Course>>{
            override fun onFailure(call: Call<List<Course>>, t: Throwable){
                Log.e("onFailure:", t.message ?: "unknown error")
            }

            override fun onResponse(
                call: Call<List<Course>>,
                response: Response<List<Course>>
            ){
                Log.e("onResponse:", response.body()?.toString() ?: "unknown error")
                response.body()?.let{
                    adapter.setDatas(it)//更新UI
                }
            }
        })
    }
  

    inner class StudyAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        private  val  courses = mutableListOf<Course>()
        fun setDatas(datas: List<Course>) {
            if (datas.isNotEmpty()){
                courses.addAll(datas)
                notifyDataSetChanged() //這個(gè)命令會(huì)重新執(zhí)行g(shù)etItemCount和onBindViewHolder
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val itemView = LayoutInflater.from(context).inflate(R.layout.item_view_linear_vertical, parent, false)
            return StudyViewHolder(itemView)
        }

        // 重寫(xiě)執(zhí)行這里才會(huì)刷新
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val course = courses[position]
//            holder.itemView.item_image.setImageResource(R.drawable.ic_dashboard_black_24dp)//本地圖片
          
            //設(shè)置圓角
            val options = RequestOptions()
                .transform(RoundedCorners(10))//設(shè)置圓角
                        //添加網(wǎng)絡(luò)圖片
            Glide.with(context!!)
                .load(course.poster)//設(shè)置圖片地址
                    .apply ( options )
                .into(holder.itemView.item_course_poster)//綁定控件
            holder.itemView.item_title.text = course.title
            holder.itemView.item_message.text="內(nèi)容${position} "
        }

        override fun getItemCount(): Int {
            return courses.size
        }

        inner class StudyViewHolder(view: View):RecyclerView.ViewHolder(view){

        }
    }
}

12楼雹、列表的增刪改查

class StudyFragment: Fragment(R.layout.fragment_study) {//關(guān)聯(lián)布局
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = StudyAdapter()
        recycler_view.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
        recycler_view.adapter = adapter

        //點(diǎn)擊增加按鈕
        tab_add_course.setOnClickListener{
            val course = Course(
                label = "Android學(xué)習(xí)基礎(chǔ)",
                poster = "https://www.songyubao.com/static/book/assets/icon-android.jpeg",
                progress = "100%",
                title = "Android RecyclerView基礎(chǔ)學(xué)習(xí)"
            )
            adapter.addCourse(course)
            recycler_view.scrollToPosition(0)//滑動(dòng)到第0個(gè)位置
        }
          //點(diǎn)擊刪除按鈕
        tab_delete_course.setOnClickListener{
            adapter.deleteCourse(0)
        }
        //點(diǎn)擊更新按鈕
        tab_update_course.setOnClickListener{
            adapter.updateCourse(0, "80%")
        }
      ...
    }

    inner class StudyAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        private  val  courses = mutableListOf<Course>()
        fun setDatas(datas: List<Course>) {
            if (datas.isNotEmpty()){
                courses.addAll(datas)
                notifyDataSetChanged() //這個(gè)命令會(huì)重新執(zhí)行g(shù)etItemCount和onBindViewHolder
            }
        }

        fun addCourse(course: Course){
//            courses.add(0, course)
//            notifyItemChanged(0)

            courses.add(course)
            //notifyDataSetChanged()//更新整個(gè)列表
            notifyItemChanged(courses.size - 1)
        }

        fun deleteCourse(position: Int){
            courses.removeAt(position)
            //notifyDataSetChanged()//更新整個(gè)列表
            notifyItemRemoved(position)
        }

        fun updateCourse(position: Int, progress:String){
            val course = courses[position]
            course.progress = progress
            //notifyDataSetChanged()//更新整個(gè)列表
            notifyItemChanged(position)
        }
      ...

AS操作小技巧

  1. 查看Kotlin編譯之后的字節(jié)碼, 有助于我們深入理解kotlin語(yǔ)言, 有兩種方式:
    • Shift鍵兩次, 輸入Show kotlin
    • Tools->Kotlin->Show Kotlin Bytecode
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末模孩,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子贮缅,更是在濱河造成了極大的恐慌榨咐,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件谴供,死亡現(xiàn)場(chǎng)離奇詭異块茁,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)桂肌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)数焊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人崎场,你說(shuō)我怎么就攤上這事佩耳。” “怎么了谭跨?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵干厚,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我螃宙,道長(zhǎng)蛮瞄,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任谆扎,我火速辦了婚禮挂捅,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘堂湖。我一直安慰自己闲先,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布无蜂。 她就那樣靜靜地躺著饵蒂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪酱讶。 梳的紋絲不亂的頭發(fā)上退盯,一...
    開(kāi)封第一講書(shū)人閱讀 48,970評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音泻肯,去河邊找鬼渊迁。 笑死,一個(gè)胖子當(dāng)著我的面吹牛灶挟,可吹牛的內(nèi)容都是我干的琉朽。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼稚铣,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼箱叁!你這毒婦竟也來(lái)了墅垮?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤耕漱,失蹤者是張志新(化名)和其女友劉穎算色,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體螟够,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡灾梦,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了妓笙。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片若河。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖寞宫,靈堂內(nèi)的尸體忽然破棺而出萧福,到底是詐尸還是另有隱情,我是刑警寧澤辈赋,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布鲫忍,位于F島的核電站,受9級(jí)特大地震影響炭庙,放射性物質(zhì)發(fā)生泄漏饲窿。R本人自食惡果不足惜煌寇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一焕蹄、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧阀溶,春花似錦腻脏、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至击纬,卻和暖如春鼎姐,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背更振。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來(lái)泰國(guó)打工炕桨, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人肯腕。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓献宫,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親实撒。 傳聞我的和親對(duì)象是個(gè)殘疾皇子姊途,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容