实现效果图
实现步骤
1.布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:background="@color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:layout_scrollFlags="scroll"
android:layout_width="match_parent">
<EditText
android:textSize="16sp"
android:hint="搜索您感兴趣的内容"
android:background="#fff"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/list"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
2.填充数据
class JDScrolActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_jd_scrol)
//设置tab栏
tab_layout_title.addTab(tab_layout_title.newTab().setText("财经"))
tab_layout_title.addTab(tab_layout_title.newTab().setText("财经"))
tab_layout_title.addTab(tab_layout_title.newTab().setText("财经"))
tab_layout_title.addTab(tab_layout_title.newTab().setText("财经"))
tab_layout_title.addTab(tab_layout_title.newTab().setText("财经"))
list.layoutManager = LinearLayoutManager(this)
list.adapter = RecycleViewAdapter()
}
class RecycleViewAdapter : RecyclerView.Adapter<RecycleViewAdapter.RecycleViewViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecycleViewViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.simple_item, parent, false)
return RecycleViewViewHolder(view)
}
override fun getItemCount(): Int {
return 10
}
override fun onBindViewHolder(holder: RecycleViewViewHolder, position: Int) {
}
class RecycleViewViewHolder(view: View) :RecyclerView.ViewHolder(view){
}
}
}
关键点
使用了系统自带的Behavior