Kotlin第六章:完善页面demo

习狐若
2023-12-01

1. Glide框架

1. 引用使用

学习地址 https://www.jianshu.com/p/ce07a9b335bb

app/build.gradle中添加相关依赖

plugins {
    id 'kotlin-kapt'
}
... 
dependencies {
    // 引入 Glide框架加载网络图片
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    kapt 'com.github.bumptech.glide:compiler:4.9.0'
}

2. 错误排除

  1. 运行时提示 Duplicate class found

引入glide的时候与com.android.support包名重复了,排除之后clean一下

dependencies {
    // 主要是这个包的问题,排斥com.android.support下的所有包
    implementation('com.github.bumptech.glide:glide:4.9.0'){
        exclude group: 'com.android.support'
    }
    kapt 'com.github.bumptech.glide:compiler:4.9.0'
}

如果运行之后还是提示 ClassNotDefined则,将这个exclude删除掉,还原成原来的样子,在gradle.properties中添加下列代码

android.useAndroidX=true
android.enableJetifier=true

2. 修改页面demo

1. 添加解析实体类

package com.example.myapplication

data class Course(
    val label: String,
    val poster: String,
    val progress: String,
    val title: String
)

2. 添加相关接口

  • 修改Retrofit中的url路径
private const val jsonUrl = "https://songyubao.com/"
// 创建出来 retrofit的对象
private var retrofit = Retrofit.Builder()
.client(clientWithHttpLoggingInterceptor)
.baseUrl(jsonUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
  • 添加接口
package com.example.myapplication.http

import com.example.myapplication.Course
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface ApiServiceKotlin  {
    
	// 获取课程列表json
    @GET("static/book/assets/study.json")
    fun getStudy(): Call<List<Course>>
}

3. 修改fragment

第三行的tab切换页添加三个按钮

<?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"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
   
    <!-- 第三行切换   -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="我的课程"
            android:textStyle="bold"
            android:id="@+id/tab_course"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="我的专栏"
            android:textStyle="bold"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:id="@+id/tab_article"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="增加课程"
            android:textStyle="bold"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:id="@+id/tab_add"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="删除课程"
            android:textStyle="bold"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:id="@+id/tab_del"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="编辑课程"
            android:textStyle="bold"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:id="@+id/tab_edit"/>

    </LinearLayout>
</LinearLayout>

3. 添加按钮事件

package com.example.myapplication.ui.study

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
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.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.myapplication.Course
import com.example.myapplication.R
import com.example.myapplication.http.ApiServiceKotlin
import com.example.myapplication.http.RetrofitUtil
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_home.recycler_view
import kotlinx.android.synthetic.main.fragment_study.*
import kotlinx.android.synthetic.main.item_study.view.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class StudyFragment: Fragment(R.layout.fragment_study) {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recycler_view.layoutManager = LinearLayoutManager(context)
        var adapter = StudyAdapter()
        recycler_view.adapter = adapter
        // 获取ApiServiceKotlin实体对象
        var serviceKotlin = RetrofitUtil.create(ApiServiceKotlin::class.java)
        // 从远程服务器获取数据
        serviceKotlin.getStudy()
            .enqueue(object: Callback<List<Course>>{
                override fun onResponse(
                    call: Call<List<Course>>,
                    response: Response<List<Course>>
                ) {
                    Log.e("getStudy() Success",response.body()?.toString()?: "unknown reason")
                    response.body()?.let{
                        adapter.refreshData(it)
                    }
                }

                override fun onFailure(call: Call<List<Course>>, t: Throwable) {
                    Log.e("getStudy Failure",t.message?: "unknown error")
                }

            })

        var course = Course("Android添加课程",
            "https://songyubao.com/static/book/assets/icon-android-4.jpeg",
            "99%",
            "测试")
		
        // 给相关按钮添加点击事件
        // 不必要给三个方法单独写,直接用notifyDataSetChanged()就好了
        tab_add.setOnClickListener {
            adapter.addCourse(course)
            // 如果是添加到列表的第一个元素的话,就需要手动滑动一下,调用这个方法可以省略这个步骤
            recycler_view.scrollToPosition(0)
        }
        tab_del.setOnClickListener {
            adapter.delCourse(2)
        }
        tab_edit.setOnClickListener {
            adapter.editCourse(course)
        }
    }

    inner class StudyAdapter : RecyclerView.Adapter<StudyViewHolder>() {
        private val courses = mutableListOf<Course>()
        public fun refreshData(dataList: List<Course>){
            if(dataList.isNotEmpty()){
                courses.addAll(dataList)
                notifyDataSetChanged()
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudyViewHolder {
            var view = LayoutInflater.from(context)
                .inflate(R.layout.item_study, parent, false)
            return StudyViewHolder(view)
        }
		
        // 这里因为从网络获取连接,所以不能固定长度
        override fun getItemCount(): Int {
            return courses.size
        }

        @SuppressLint("CheckResult")
        override fun onBindViewHolder(holder: StudyViewHolder, position: Int) {
            val  course = courses[position]
            holder.itemView.item_course_title.text = course.title
            holder.itemView.item_course_label.text = course.label
            holder.itemView.item_course_progress.text = course.progress
            val options = RequestOptions().transform(RoundedCorners(100))
			// 使用Glide绑定网络图片
            Glide.with(context!!)
                .load(course.poster.replace("www.",""))
                .apply(options)
                .into(holder.itemView.item_course_logo)
            //holder.itemView.item_course_logo.setImageResource(R.drawable.logo)

        }

        fun addCourse(course: Course){
            courses.add(0,course)
            // 往列表第一行插入
            notifyItemInserted(0)
            //
            //notifyItemInserted(courses.size - 1)
        }

        fun delCourse(position: Int){
            courses.removeAt(position)
            notifyItemRemoved(position)
        }

        fun editCourse(course: Course){
            var position = courses.indexOf(course)
            println(position)
            notifyItemChanged(position,course)
        }

    }

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

}
 类似资料: