看到不少應用的設置界面都有圓角效果的列表,相似下面的android
下面說說個人實現原理:繼承LinearLayout,而後設置一個自定義的TabAdapter,相似於listview,添加一個setAdapter()方法,這個方法就是將子視圖加入,而後設置背景選擇器效果;還能夠添加風格不一樣的視圖,經過addview方法,最後必定要調用commit方法,設置子視圖的背景,對於背景有三種狀況,中間項四角都是圓角,頂部圓角和頂部圓角效果git
自定義TabAdapter抽象類,是要繼承便可:github
package com.allen.tabview; import android.view.View; /** * @package:com.allen.tabview * @author:Allen * @email:jaylong1302@163.com * @data:2013-7-26 下午2:49:51 * @description:適配器 */ public abstract class TabAdapter { public abstract int getCount(); public abstract Object getItem(int position); public abstract View getView(int position); }
接下來是自定義的TabViewide
package com.allen.tabview; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; /** * @package:com.allen.tabview * @author:Allen * @email:jaylong1302@163.com * @data:2013-7-26 下午2:48:36 * @description:圓角表格 */ public class TabView extends LinearLayout { TabAdapter adapter; /** 子視圖數量 */ int size = 0; public TabView(Context context) { super(context); init(); } public TabView(Context context, AttributeSet attrs) { super(context, attrs); init(); } void init() { this.setOrientation(LinearLayout.VERTICAL); this.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); this.setBackgroundResource(R.drawable.background_view_rounded_container); } /** 設置適配器 */ public void setAdapter(TabAdapter adapter) { this.adapter = adapter; // 遍歷當前的adapter if (adapter != null) { size = adapter.getCount(); for (int i = 0; i < size; i++) { View child = adapter.getView(i); this.addView(child); } commit(); } } @Override public void addView(View child) { // TODO Auto-generated method stub super.addView(child); child.setClickable(true); } /** 調用addView以後執行的方法 */ public void commit() { int len = this.getChildCount(); if (len > 1) {// 多項內容 for (int i = 0; i < len; i++) { View child = this.getChildAt(i); if (i == 0) {// 頂部 child.setBackgroundResource(R.drawable.background_view_rounded_top); } else if (i > 0 && i < len - 1) {// 中間 child.setBackgroundResource(R.drawable.background_view_rounded_middle); } else if (i == len - 1) {// 底部 child.setBackgroundResource(R.drawable.background_view_rounded_bottom); } } } else if (len == 1) {// 一項內容 View child = this.getChildAt(0); child.setBackgroundResource(R.drawable.background_view_rounded_single); } } public interface TabItemClickListener { void onClick(int position, View v); } TabItemClickListener itemClick; public void setOnItemClickListener(final TabItemClickListener itemClick) { this.itemClick = itemClick; // 綁定監聽事件 for (int i = 0; i < size; i++) { final int index = i; View childView = this.getChildAt(i); childView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (itemClick != null) { itemClick.onClick(index, v); } } }); } } }
最後有一點,對於整個最外層的圓角背景是使用inset,那樣自動加入了分隔線效果this
整個項目在github上面, 須要的能夠clone和fok。。。spa