HomeFragment.dart通过监听RecyclerView的滑动事件来动态啊设置背景的透明度来实现
package com.example.takeout.ui.fragment
import 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.find
class HomeFragment : Fragment() {
lateinit var homeRvAdapter: HomeRvAdapter//延迟初始化
lateinit var rvHome: RecyclerView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = View.inflate(activity, R.layout.fragment_home, null)
rvHome = view.find<RecyclerView>(R.id.rv_home)
//上下布局
rvHome.layoutManager = LinearLayoutManager(activity)
homeRvAdapter = HomeRvAdapter(activity)
rvHome.adapter = homeRvAdapter
distance = 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<String> = ArrayList<String>()
var sum: Int = 0
var distance: Int = 0
var alpha = 55
private 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 += dy
if (sum > distance) {
alpha = 255
} else {
alpha = sum * 200 / distance
alpha += 55
}
Log.e("home", "alpha:$alpha")
ll_title_container.setBackgroundColor(Color.argb(alpha, 0x31, 0x90, 0xe8))
}
})
}
}
效果如下