1、RecyclerView列表布局
在item_view_linear_vertical.xml中:
在fragment_study.xml中:
在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) {//关联布局
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// 需要先安装扩展插件, 就可以直接通过id名访问控件了
recycler_view.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
recycler_view.adapter = StudyAdapter()
}
// inner 用于声明StudyAdapter是StudyFragment的内部类
inner class StudyAdapter : RecyclerView.Adapter() {
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控件设置图片的三种方式:
holder.itemView.item_image.setImageResource(R.drawable.ic_dashboard_black_24dp)//✅
holder.itemView.item_image.setImageDrawable(
ContextCompat.getDrawable(
context!!,// !!表示说明此对象不为空
R.drawable.icon_jetpack
)
)
holder.itemView.item_image.setImageBitmap(BitmapFactory.decodeResource(context!!.resource, R.drawable.icon_jetpack))
holder.itemView.item_title.text="标题$position"
holder.itemView.item_message.text="内容${position} 能接收到分离焦虑世纪东方垃圾水电费拉伸点击分类计数法 打开了施法距离卡机士大夫撒的发生撒旦法阿斯顿发安达市 发"
}
override fun getItemCount(): Int {
return 20
}
inner class StudyViewHolder(view: View):RecyclerView.ViewHolder(view){
}
}
}
2、GradLayoutManager网格布局
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的内部类
inner class MyAdapter: RecyclerView.Adapter(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyVIewHolder{
//访问外部类的context对象
val itemView = LayoutInflater.from(context)
.inflate(R.layout.item_view_grid, parent, false)
return MyViewHolder(itemView)
}
// 告诉列表有多少条数据
override fun getItemCount(): Int{
return 20
}
//数据绑定
override fun onBindViewHolder(holder: MyViewHolder, position: Int){
/// 在代码中给image控件设置图片的三种方式:
holder.itemView.item_image.setImageResource(R.drawable.icon_jetpack)//✅
holder.itemView.item_image.setImageDrawable(
ContextCompat.getDrawable(
context!!,// !!表示说明此对象不为空
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的内部类
inner class MyAdapter: RecyclerView.Adapter(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyVIewHolder{
//访问外部类的context对象
val itemView = LayoutInflater.from(context)
.inflate(R.layout.item_view_grid, parent, false)
return MyViewHolder(itemView)
}
// 告诉列表有多少条数据
override fun getItemCount(): Int{
return 20
}
//数据绑定
override fun onBindViewHolder(holder: MyViewHolder, position: Int){
/// 在代码中给image控件设置图片的三种方式:
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)//取消设置单行显示
} else {
holder.itemView.item_message.setSingleLine(true)//单行显示
}
holder.itemView.item_message.text = "xxxxx"
}
}
class MyViewHolder(view: View): RecyclerView.ViewHolder(view){
}
}
4、快速实现圆角阴影的组件
// 这一行代码, 放在顶部layout标签中声明
xmlns:app="http://schemas.android.com/apk/res-auto"
...
AndroidStudio配置阿里云镜像 2021.02.25 10:46 2020浏览
https://www.imooc.com/article/315290
Mac IDEA配置阿里云国内镜像 发布于 2020-07-30
https://segmentfault.com/a/1190000023086534
警告:You have JVM property “https.proxyHost“ set to “127.0.0.1“
https://www.jianshu.com/p/9cec82d9498e
5、网络请求框架OKHTTP--GET请求
在app->manifests->AndroidManifest.xml添加网络访问权限:
在app/build.gradle
的dependencies
中添加下面的依赖
dependencies {
...
implementation("com.squareup.okhttp3:okhttp:4.9.0")
// 网络请求日志打印
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需要创建实例对象
// 使用object的声明方式, 就没有必要构建它的实例对象了, 直接可以类.方法调用
object HiOkHttp {
private val BASE_URL="http://123.56.232.18:8080/serverdemo"
//全局中只有一份
val client = OkHttpClient.Builder() //builder构造者设计模式
.connectTimeout(10, TimeUnit.SECONDS) //连接超时时间
.readTimeout(10, TimeUnit.SECONDS) //读取超时
.writeTimeout(10, TimeUnit.SECONDS) //写超时,也就是请求超时
.build();
// Android分为主线程和子线程
// 主线程就是APP一启动后, Android framework层会启动一个线程, 主线程(UI线程)
// 子线程 -- 可以通过new Thread().start()创建
//方式一: 同步GET请求
fun get(url: String) {//网络请求接口
Thread(Runnable {//开启子线程
//构造请求体
val request: Request = Request.Builder()
// .url(url)
.url("$BASE_URL/user/query?userId=1600932269")
.build()
//构造请求对象
val call: Call = client.newCall(request)
// 通过.execute()发起同步请求--同步执行
val response = call.execute()
val body = response.body?.string()
// println("get response :${body}")
Log.e("OKHTTP","get response :${body}")
}).start()
}
//方式二: 异步GET请求
fun getAsync(url: String) {//网络请求接口
//构造请求体
val request: Request = Request.Builder()
// .url(url)
.url("$BASE_URL/user/query?userId=1600932269")
.build()
//构造请求对象
val call: Call = client.newCall(request)
// 通过.enqueue()发起异步请求--异步执行
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","get response :${body}")
}
})
}
}
在MainActivity.kt中使用:
HiOkHttp.get()
6、网络请求框架OKHTTP--POST请求
http://123.56.232.18:8080/serverdemo/swagger-ui.html#/tag-list-controller/toggleTagFollowUsingPOST
/// 同步表达提交
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以后, 读取外部存储卡文件都是需要动态申请权限的
fun postAsyncMultipart(context: Context) {
val file = File(Environment.getExternalStorageDirectory(), "1.png")// 文件目录, 文件名称
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请求---提交字符串
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默认拦截器
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构造者设计模式
.connectTimeout(10, TimeUnit.SECONDS) //连接超时时间
.readTimeout(10, TimeUnit.SECONDS) //读取超时
.writeTimeout(10, TimeUnit.SECONDS) //写超时,也就是请求超时
.addInterceptor(httpLoggingInterceptor)//使用默认拦截器
.build();
}
....
}
使用自定义拦截器:
/// ①在LoggingInterceptor.kt中:
package com.dbc.bckotlinall.http
import android.util.Log
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer
/// 拦截器要做的事: 打印拦截请求时的接口、携带哪些参数
class LoggingInterceptor: Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val time_start = System.nanoTime()
val request = chain.request() //获取request对象
val response = chain.proceed(request)//获取response对象
val buffer = Buffer()
request.body?.writeTo(buffer)
val requestBodyStr = buffer.readUtf8()//把request.body转换成字符串
//打印请求前的: 地址 和 请求参数
Log.e("OKHTTP",String.format("Sending request %s with params %s",request.url, requestBodyStr))
val bussinessData = response.body?.string()?:"response body null" //读取输出流,获取接口返回的数据
/*由于OKHTTP的工作原理: 一旦调用了response.body?.string()方法, 今后再也不能用response去读取它的响应流了.
*
* 这也就意味着: onResponse回调函数中,再次读取response.body?.string()就会报错. 这是OKHTTP的工作原理决定的.
*
* 对于Response响应流只能读取一次的解决办法是: 返回一个新的Response.
* */
val mediaType = response.body?.contentType()
val newBody = ResponseBody.create(mediaType, bussinessData)
val newResponse = response.newBuilder().body(newBody).build()
val time_end = System.nanoTime()
//打印请求后的结果
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来解析网络请求响应
在app/build.gradle
中添加以下依赖配置
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转换成对象
val json ="{\"uid\":\"00001\",\"userName\":\"Freeman\",\"telNumber\":\"13000000000\"}"
val gson = Gson()//构建gson对象
// 在kotlin中传入class类型, 需要xxx::class.java 格式
val account:Account = gson.fromJson(json, Account::class.java)
println("fromJson: ${account.toString()}")
/// 把对象转换成JSON
val accountJson = gson.toJson(account)
println("toJson: ${accountJson}")
/// 将JSON转换成集合
val jsonList= "[{\"uid\":\"00001\",\"userName\":\"Freeman\",\"telNumber\":\"13000000000\"}]"
val accountList: List = gson.fromJson(jsonList, object:TypeToken>(){}.type)
println("fromJson to List:${accountList.size}")
/// 将集合转化成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: 首先选中这几个字段-->右键"Generate"-->选择"toString()"-->全选
override fun toString(): String {
return "Account(uid='$uid', userName='$userName', password='$password', telNumber='$telNumber')"
}
}
如果对象模型使用data class, 就可以不用指定初始值了:
data class Account(
var uid:String = "111",
var userName:String,
var password:String,
var telNumber:String
)
使用插件快速生成复杂的数据模型 -- JsonToKotlin插件:
sp1.在网站 https://github.com/wuseal/JsonToKotlinClass/releases/ 下载最新版本zip包
sp2.在AS-->Preferences-->Plugins-->点击"设置"按钮, 选择"install Plugin from Disk..."--->选择下载的包,点击"OK", 重启IDE
使用插件:
在空白的地方, 右键选择"Generate"-->选择"Kotlin data classes from JSON"-->将JSON字符串拷贝到这里-->点击"Format", 输入"Class Name: xxx", 选择"Generate" --> 就生成了xxx对象模型
val userModelJson = "{ ... }"
val userResponse:UserResponse! = gson.fromJson(userModelJson, UserResponse::class.java)
println("userResponse: $userResponse")
9、RESTFUL网络请求框架Retrofit
retrofit注解驱动型上层网络请求框架, 使用注解来简化请求, 大体分为以下几类:
- 用于标注网络请求的注解
- 标记网络请求参数的注解
- 用于标记网络请求和响应格式的注解
添加依赖:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0' //json转换
在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构造者设计模式
.connectTimeout(10, TimeUnit.SECONDS) //连接超时时间
.readTimeout(10, TimeUnit.SECONDS) //读取超时
.writeTimeout(10, TimeUnit.SECONDS) //写超时,也就是请求超时
.addInterceptor(LoggingInterceptor())
.build();
private val retrofit = Retrofit.Builder()
.client(client)//配置OKHTTP网络请求的一个对象
.baseUrl("http://123.56.232.18:8080/serverdemo/")//配置网络请求的域名
.addConverterFactory(GsonConverterFactory.create())//数据转换器: 自动转换成数据模型
.build();
///定义一个泛型方法
fun create(clazz: Class): T {
return retrofit.create(clazz)
}
}
/// 定义一个接口文件, 编写网络请求方法
interface APIService{
@GET(value="user/query")
fun queryUser(@Query(value="userId",encoded = true) userId: String):Call
//UserResponse: 要转换的数据模型对象类
}
在MainActivity.kt中使用:
val apiService = HiRetrofit.create(APIService::class.java)
// 此时onFailure 和 onResponse的回调都是在主线程的; 但OKHTTP的回调是在子线程的,如果UI操作还需要回到主线程.
apiService.queryUser("1600932269").enqueue(object: Callback{
override fun onFailure(call: Call, t: Throwable) {
Log.e("Retrofit","失败原因 :${t.message}")
}
override fun onResponse(call: Call, response: Response) {
val body = response.body?.string()
Log.e("Retrofit","get response :${body}")
}
})
10、网络图片的加载
在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、数据请求与绑定
class StudyFragment: Fragment(R.layout.fragment_study) {//关联布局
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>{
override fun onFailure(call: Call>, t: Throwable){
Log.e("onFailure:", t.message ?: "unknown error")
}
override fun onResponse(
call: Call>,
response: Response>
){
Log.e("onResponse:", response.body()?.toString() ?: "unknown error")
response.body()?.let{
adapter.setDatas(it)//更新UI
}
}
})
}
inner class StudyAdapter : RecyclerView.Adapter() {
private val courses = mutableListOf()
fun setDatas(datas: List) {
if (datas.isNotEmpty()){
courses.addAll(datas)
notifyDataSetChanged() //这个命令会重新执行getItemCount和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)
}
// 重写执行这里才会刷新
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val course = courses[position]
// holder.itemView.item_image.setImageResource(R.drawable.ic_dashboard_black_24dp)//本地图片
//设置圆角
val options = RequestOptions()
.transform(RoundedCorners(10))//设置圆角
//添加网络图片
Glide.with(context!!)
.load(course.poster)//设置图片地址
.apply ( options )
.into(holder.itemView.item_course_poster)//绑定控件
holder.itemView.item_title.text = course.title
holder.itemView.item_message.text="内容${position} "
}
override fun getItemCount(): Int {
return courses.size
}
inner class StudyViewHolder(view: View):RecyclerView.ViewHolder(view){
}
}
}
12、列表的增删改查
class StudyFragment: Fragment(R.layout.fragment_study) {//关联布局
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
//点击增加按钮
tab_add_course.setOnClickListener{
val course = Course(
label = "Android学习基础",
poster = "https://www.songyubao.com/static/book/assets/icon-android.jpeg",
progress = "100%",
title = "Android RecyclerView基础学习"
)
adapter.addCourse(course)
recycler_view.scrollToPosition(0)//滑动到第0个位置
}
//点击删除按钮
tab_delete_course.setOnClickListener{
adapter.deleteCourse(0)
}
//点击更新按钮
tab_update_course.setOnClickListener{
adapter.updateCourse(0, "80%")
}
...
}
inner class StudyAdapter : RecyclerView.Adapter() {
private val courses = mutableListOf()
fun setDatas(datas: List) {
if (datas.isNotEmpty()){
courses.addAll(datas)
notifyDataSetChanged() //这个命令会重新执行getItemCount和onBindViewHolder
}
}
fun addCourse(course: Course){
// courses.add(0, course)
// notifyItemChanged(0)
courses.add(course)
//notifyDataSetChanged()//更新整个列表
notifyItemChanged(courses.size - 1)
}
fun deleteCourse(position: Int){
courses.removeAt(position)
//notifyDataSetChanged()//更新整个列表
notifyItemRemoved(position)
}
fun updateCourse(position: Int, progress:String){
val course = courses[position]
course.progress = progress
//notifyDataSetChanged()//更新整个列表
notifyItemChanged(position)
}
...
AS操作小技巧
- 查看Kotlin编译之后的字节码, 有助于我们深入理解kotlin语言, 有两种方式:
- Shift键两次, 输入Show kotlin
- Tools->Kotlin->Show Kotlin Bytecode