1、最近有一个需求,需要对ListView和recyclerView是否应淡化边缘;
2、在开发中遇到问题发现fadingEdge=“vertical”,fadingEdgeLength="150dp"不生效,于是各种尝试,最终需要增加fadingEdgeLength=“150dp”,requiresFadingEdge="vertical"就可生效;
3、下面我们来看code:
1)先看一下xml如何设置:
activity_main.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" >
<!-- requiresFadingEdge:拉滚动条时 ,边框渐变的放向,none(边框颜色不变),horizontal(水平方向颜色变淡),vertical(垂直方向颜色变淡) -->
<!-- fadingEdgeLength:设置边框渐变的长度 -->
<com.application.application.MyListView
android:id="@+id/main_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fadingEdgeLength="150dp"
android:requiresFadingEdge="vertical"
/>
</LinearLayout>
2)在设置这个属性如果出现不生效,可参考如下重写一下getTopFadingEdgeStrength和getBottomFadingEdgeStrength;
public class MyListView extends ListView {
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected float getTopFadingEdgeStrength() {
return 1f;
}
@Override
protected float getBottomFadingEdgeStrength() {
return 1f;
}
}
3)我们来可以先主activity实现,其也可动态设置渐变效果,code里也已经标准,可参考;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (MyListView) findViewById(R.id.main_list);
// 也可以在代码中动态设置边框渐变的长度
//lv.setFadingEdgeLength(150);
//垂直方向颜色变淡
// lv.setVerticalFadingEdgeEnabled(true);
// 去掉分割黑线
//lv.setDivider(null);
String[] data = new String[] { "item1", "item2", "item3", "item4",
"item5", "item6", "item7", "item8", "item9", "item10",
"item11", "item12","item13", "item14", "item15", "item16", "item17",
"item18", "item19" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
lv.setAdapter(adapter);
}
}
4)recyclerView和ListView设置相同,这里代码就不贴了,
比如向让recyclerView水平方向展示,在动态设置的时候,需要注意,要将setOrientation()和requiresFadingEdge一致,详细code就不写了,我们看一下要注意的地方;
recyclerView.setFadingEdgeLength(150);
recyclerView.setHorizontalFadingEdgeEnabled(true);
//recyclerView.setVerticalFadingEdgeEnabled(true);
...
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
5)下面来一张效果图:
recyclerView渐变效果code下载链接https://download.csdn.net/download/xiao_yuanjl/12275810