我寫這篇文章受到了kiritor的專欄發表的博文Android UI控制項之ListView實現圓角效果的啟發。
先看:
首先,你得寫一個類我們命名為CornerListView
/** * 圓角ListView樣本 * @Description: 圓角ListView樣本 * @FileName: CornerListView.java */public class CornerListView extends ListView { public CornerListView(Context context) { super(context); } public CornerListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public CornerListView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: int x = (int) ev.getX(); int y = (int) ev.getY(); int itemnum = pointToPosition(x, y); if (itemnum == AdapterView.INVALID_POSITION) break; else{ if(itemnum==0){ if(itemnum==(getAdapter().getCount()-1)){ setSelector(R.drawable.app_list_corner_round); }else{ setSelector(R.drawable.app_list_corner_round_top); } }else if(itemnum==(getAdapter().getCount()-1)) setSelector(R.drawable.app_list_corner_round_bottom); else{ setSelector(R.drawable.app_list_corner_shape); } } break; case MotionEvent.ACTION_UP: break; } return super.onInterceptTouchEvent(ev); }}
其中,app_list_corner_round
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:startColor="#BFEEFF" android:endColor="#40B9FF" android:angle="270"/> <corners android:topLeftRadius="6dip" android:topRightRadius="6dip" android:bottomLeftRadius="6dip" android:bottomRightRadius="6dip"/></shape>
app_list_corner_round_top
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:startColor="#BFEEFF" android:endColor="#40B9FF" android:angle="270"/> <corners android:topLeftRadius="6dip" android:topRightRadius="6dip"/></shape>
app_list_corner_round_bottom
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:startColor="#BFEEFF" android:endColor="#40B9FF" android:angle="270"/> <corners android:bottomLeftRadius="6dip" android:bottomRightRadius="6dip" /></shape>
app_list_corner_shape
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:startColor="#BFEEFF" android:endColor="#40B9FF" android:angle="270"/></shape>
寫好了之後,就可以在你的代碼中直接像listview一樣調用。