HomeFragment.dart通过监听RecyclerView的滑动事件来动态啊设置背景的透明度来实现
package com.example.takeout.ui.fragmentimport android.app.Fragment
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.takeout.R
import com.example.takeout.ui.adapter.HomeRvAdapter
import kotlinx.android.synthetic.main.fragment_home.*
import org.jetbrains.anko.findclass HomeFragment : Fragment() {lateinit var homeRvAdapter: HomeRvAdapter//延迟初始化lateinit var rvHome: RecyclerViewoverride fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {val view = View.inflate(activity, R.layout.fragment_home, null)rvHome = view.find(R.id.rv_home)//上下布局rvHome.layoutManager = LinearLayoutManager(activity)homeRvAdapter = HomeRvAdapter(activity)rvHome.adapter = homeRvAdapterdistance = 120.dp2px()return view}fun Int.dp2px(): Int {return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,toFloat(), resources.displayMetrics).toInt()}override fun onActivityCreated(savedInstanceState: Bundle?) {super.onActivityCreated(savedInstanceState)initData()}val datas: ArrayList = ArrayList()var sum: Int = 0var distance: Int = 0var alpha = 55private fun initData() {for (i in 0 until 100) {datas.add("我是商家:" + i)}homeRvAdapter.setData(datas)//有数据可以滚动才可以监听滚动事件,设置标题的透明效果rvHome.setOnScrollListener(object : RecyclerView.OnScrollListener() {override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {if (recyclerView != null) {super.onScrollStateChanged(recyclerView, newState)}}override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {if (recyclerView != null) {super.onScrolled(recyclerView, dx, dy)}sum += dyif (sum > distance) {alpha = 255} else {alpha = sum * 200 / distancealpha += 55}Log.e("home", "alpha:$alpha")ll_title_container.setBackgroundColor(Color.argb(alpha, 0x31, 0x90, 0xe8))}})}}
效果如下