我有一个顶部和底部有圆角的列表视图.看起来像这个图像:
但是当我单击ListView的顶部和底部时,List Item的背景是矩形而不是圆形作为ListView的顶部和底部背景.喜欢这个图片:
如何解决这个问题?
这是我的代码:
1 / list_activity.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#cacaca"> <ListView android:id="@+id/listView3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:background="@drawable/list_border" android:listSelector="@drawable/list_selector"/> </LinearLayout>
2 / list_border.xml
<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#fff"/> <corners android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp" android:topLeftRadius="10dp" android:topRightRadius="10dp"/> </shape>
3 / list_selector.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@color/colorPrimary" /> </selector>
4 / ListActivity.java
ListView listView = (ListView)findViewById(R.id.listView3); ArrayList<String> listItems = new ArrayList<>(); for(int i=0;i<20;i++){ listItems.add(""+i); } ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_selectable_list_item,listItems); listView.setAdapter(adapter);
解决方法
这个解决方案并不漂亮,但它可以满足您的需求.想法是反转角落并将它们绘制为前景:
ListView包装在FrameLayout中:
<FrameLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_margin="10dp" android:foreground="@drawable/inverted_corners" android:layout_weight="1"> <ListView android:id="@+id/listView3" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" android:listSelector="@drawable/list_selector" /> </FrameLayout>
将前景(drawable / inverted_corners.xml)设置为圆孔,使用背景颜色绘制.诀窍是在形状外画一条线,而不是填充形状:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:bottom="-11dp" android:left="-11dp" android:right="-11dp" android:top="-11dp"> <shape android:shape="rectangle"> <stroke android:width="10dp" android:color="#cacaca" /> <corners android:radius="22dp" /> </shape> </item> </layer-list>
这可以确保圆角位于选择器顶部,并具有过卷效果.