一手遮天 Android - view(RecyclerView): RecyclerView 分隔线
一手遮天 Android - view(RecyclerView): RecyclerView 分隔线
示例如下:
/view/recyclerview/RecyclerViewDemo2.java
/**
* RecyclerView 分隔线
*
* 关于本例中使用的自定义的垂直线性布局的分隔线请参见
*/
package com.webabcd.androiddemo.view.recyclerview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.webabcd.androiddemo.R;
public class RecyclerViewDemo2 extends AppCompatActivity {
private RecyclerView _recyclerView;
private Button _button1;
private Button _button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_recyclerview_recyclerviewdemo2);
_recyclerView = findViewById(R.id.recyclerView1);
_button1 = findViewById(R.id.button1);
_button2 = findViewById(R.id.button2);
sample();
}
private void sample() {
_recyclerView.setLayoutManager(new LinearLayoutManager(RecyclerViewDemo2.this));
_recyclerView.setAdapter(new MyRecyclerViewAdapter(MyData.generateDataList()));
_button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
while (_recyclerView.getItemDecorationCount() > 0) {
_recyclerView.removeItemDecorationAt(0);
}
// 指定自定义分隔线(指定高度和颜色)
_recyclerView.addItemDecoration(new MyVerticalLinearLayoutManagerDivider(20, getResources().getColor(R.color.orange)));
}
});
_button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
while (_recyclerView.getItemDecorationCount() > 0) {
_recyclerView.removeItemDecorationAt(0);
}
// 指定自定义分隔线(指定高度和 Drawable 对象)
_recyclerView.addItemDecoration(new MyVerticalLinearLayoutManagerDivider(20, getResources().getDrawable(R.drawable.shape_recyclerview_divider)));
}
});
}
}
/layout/activity_view_recyclerview_recyclerviewdemo2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="指定自定义分隔线(指定高度和颜色)"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="指定自定义分隔线(指定高度和 Drawable 对象)"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
/drawable/shape_recyclerview_divider.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size android:height="20dp" />
<solid android:color="#ff00ff00" />
</shape>