做了很久的開發,看大別的大牛寫的文章,知識分享,自己學的東西都很過時,老是趕不上發展的速度,哈哈出生晚唄!Android 自定義View是Android開發人員轉型的一個重要節點啊。學了很久這塊的東西,這次遇見一個組合類型的自定義,打算記錄一下,畢竟時間長了,也會忘記。
有一個這樣的需求:
類似於京東的篩選界面,這樣點擊還能展開,一般看來也就是外層一個ListView這種,內部嵌套一個GridView唄,其實差不多吧。想的是把中間這個部分標題和內容全部抽取出來做成一個Item的view,這就是一個組合的自定義View。但是我們能想到,ListView內部item放一個GridView嵌套,肯定會出現內部的GridView不能按照預期的那種效果展開全部的,所以還要讓內部的GridView 重寫一下onMeasure方法。然後,其他的按照正常的自定義思路就可以了。這裏還有一個東西就是沒有點擊的時候我們讓他顯示3條數據,點擊後展開全部數據,我們在默認下讓GridView 的getCount()方法返回3就可以,點擊後返回數據集合的大小就可以實現。下面嘗試實現。
1.首先寫幾個屬性attr.xml文件。
假設上圖的“品牌”這個標題要用屬性值吧,我們定義它的顏色,內容和大小。
<declare-styleable name="ShaiXuanItem">
<attr name="itemTitle" format="string"/>
<attr name="itemTitleColor" format="color"/>
<attr name="itemTitleSize" format="dimension"></attr>
</declare-styleable>
2.創建一個佈局,寫上自己要的樣式
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="@color/white"
android:layout_height="wrap_content">
<RelativeLayout
android:id="@+id/rl_item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_titleName"
android:textSize="15sp"
android:text="品牌類別名"
android:padding="10dp"
android:textColor="@color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_btn_titleState"
android:textSize="15sp"
android:text="全部"
android:padding="10dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:drawablePadding="10dp"
android:drawableRight="@mipmap/down"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<!-- 此處的GridView 應該會出現嵌套衝突,不能全部展開,後邊重寫onMeasure就好-->
<GridView
android:id="@+id/grid_itemView"
android:numColumns="3"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
3.創建類ShaiXuanItem,同時創建內部GridView的適配器佈局等。
內部GridView 的item是一個簡單的佈局,可以自己寫一個CheckBox:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/checkbox_item"
android:button="@null"
android:padding="5dp"
android:text="選中的位置"
android:textSize="15sp"
android:textColor="@color/font_newGray"
android:gravity="center"
android:layout_margin="15dp"
android:background="@drawable/shaixuan_view_item_selector"
android:layout_width="match_parent"
android:layout_height="30dp" />
</LinearLayout>
GridView的適配器代碼:
public class ItemAdapter extends BaseAdapter {
private Context context;
private List<String> list;
private boolean isShowAll;
public void setShowAll(boolean showAll) {
isShowAll = showAll;
}
public ItemAdapter(Context context, List<String> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {//默認返回3,點擊後返回集合大小,外部點擊的時候,調用itemAdapter.notifyDataSetChanged();方法刷新
Log.e("TAG","getCount():"+list.size());
Log.e("TAG","Adapter-isShowAll:"+isShowAll);
if(list !=null && list.size()>3 && isShowAll ){
return list.size();
}else if(list!=null && list.size()>3 && !isShowAll ){
return 3;
}else if(list!=null && list.size()<=3){
return list.size();
}else{
return list.size();
}
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ItemViewHolder viewHolder;
View view;
if(convertView==null){
viewHolder = new ItemViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.shaixuan_view_item_layout,parent,false);//加載適配器佈局
viewHolder.checkBox_item = (CheckBox) view.findViewById(R.id.checkbox_item);
view.setTag(viewHolder);
}else{
view = convertView;
viewHolder = (ItemViewHolder) view.getTag();
}
viewHolder.checkBox_item.setText(list.get(position));
return view;
}
class ItemViewHolder{
CheckBox checkBox_item;
}
}
創建View:
public class ShaiXuanItem extends LinearLayout implements View.OnClickListener {
private static final String TAG = "ShaiXuanItem";
private TextView tv_titleName;
private TextView tv_btn_titleState;
/**
* 可以嵌套展開的GridView
*/
private ExpandGridView grid_itemView;
//private GridView grid_itemView;
private String itemTile;//標題
private int titleColor;//標題色
private float titleSize;//字體大小
private ItemAdapter itemAdapter;
private List<String> list;
private DisplayMetrics dm = this.getResources().getDisplayMetrics();
public void setList(List<String> newlist) {//將來外部設置數據
this.list = newlist;
itemAdapter.notifyDataSetChanged();//傳遞數據刷新
}
private boolean isShow = false;
public ShaiXuanItem(Context context) {
this(context,null);
initView(context);
}
public ShaiXuanItem(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
initView(context);
}
public ShaiXuanItem(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
titleSize = 15/dm.density;
LogUtils.e("TAG","density:"+dm.density);
LogUtils.e("TAG","densityDpi:"+dm.densityDpi);
TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.ShaiXuanItem,defStyleAttr,0);
itemTile = array.getString(R.styleable.ShaiXuanItem_itemTitle);
titleColor = array.getColor(R.styleable.ShaiXuanItem_itemTitleColor, Color.BLACK);
titleSize = array.getDimensionPixelSize(R.styleable.ShaiXuanItem_itemTitleSize,15);
array.recycle();
initView(context);
}
/**
* 初始化view,添加測試數據,創建內部GridView適配器
*/
private void initView(Context context) {
list = new ArrayList<>();
list.add("北京大學");
list.add("清華大學");
list.add("浙江大學");
list.add("人民大學");
list.add("蘭州大學");
list.add("東北大學");
list.add("南京大學");
itemAdapter = new ItemAdapter(context,list);
View view = LayoutInflater.from(context).inflate(R.layout.shaixuan_item_view_layout, this,true);//加載組合View的佈局,並依附於父佈局this,true表示要依附。
tv_titleName = (TextView) view.findViewById(R.id.tv_titleName);
tv_btn_titleState = (TextView) view.findViewById(R.id.tv_btn_titleState);
grid_itemView = (ExpandGridView) view.findViewById(R.id.grid_itemView);
view.findViewById(R.id.rl_item_title).setOnClickListener(this);
tv_titleName.setText(itemTile);
tv_titleName.setTextColor(titleColor);
tv_titleName.setTextSize(titleSize/dm.density);//設置標題字體大小
grid_itemView.setAdapter(itemAdapter);
}
/**
* 點擊監聽 點擊標題要讓整個GridView展開,默認GridView顯示3個數據條目
*
* @param v
*/
@Override
public void onClick(View v) {
if(itemAdapter!=null && !isShow){
isShow = true;
Log.e(TAG,"itemAdapter.setShowAll(true);");
itemAdapter.setShowAll(true);
itemAdapter.notifyDataSetChanged();
}else if(itemAdapter!=null && isShow){
isShow = false;
Log.e(TAG,"itemAdapter.setShowAll(false);");
itemAdapter.setShowAll(false);
itemAdapter.notifyDataSetChanged();
}
}
上面就是這個類,獲取了屬性,並初始化數據。最後設置標題點擊事件。
參看TextView的源碼可以知道,TextView 獲取屬性是這樣:
TypedArray a = theme.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.TextViewAppearance, defStyleAttr, defStyleRes);
TypedArray appearance = null;
int ap = a.getResourceId(
com.android.internal.R.styleable.TextViewAppearance_textAppearance, -1);
a.recycle();
if (ap != -1) {
appearance = theme.obtainStyledAttributes(
ap, com.android.internal.R.styleable.TextAppearance);
}
if (appearance != null) {
int n = appearance.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = appearance.getIndex(i);
switch (attr) {
case com.android.internal.R.styleable.TextAppearance_textColorHighlight:
textColorHighlight = appearance.getColor(attr, textColorHighlight);
break;
case com.android.internal.R.styleable.TextAppearance_textColor:
textColor = appearance.getColorStateList(attr);
break;
case com.android.internal.R.styleable.TextAppearance_textColorHint:
textColorHint = appearance.getColorStateList(attr);
break;
case com.android.internal.R.styleable.TextAppearance_textColorLink:
textColorLink = appearance.getColorStateList(attr);
break;
case com.android.internal.R.styleable.TextAppearance_textSize:
textSize = appearance.getDimensionPixelSize(attr, textSize);
break;
case com.android.internal.R.styleable.TextAppearance_typeface:
typefaceIndex = appearance.getInt(attr, -1);
break;
case com.android.internal.R.styleable.TextAppearance_fontFamily:
fontFamily = appearance.getString(attr);
break;
case com.android.internal.R.styleable.TextAppearance_textStyle:
styleIndex = appearance.getInt(attr, -1);
break;
case com.android.internal.R.styleable.TextAppearance_textAllCaps:
allCaps = appearance.getBoolean(attr, false);
break;
case com.android.internal.R.styleable.TextAppearance_shadowColor:
shadowcolor = appearance.getInt(attr, 0);
break;
case com.android.internal.R.styleable.TextAppearance_shadowDx:
dx = appearance.getFloat(attr, 0);
break;
case com.android.internal.R.styleable.TextAppearance_shadowDy:
dy = appearance.getFloat(attr, 0);
break;
case com.android.internal.R.styleable.TextAppearance_shadowRadius:
r = appearance.getFloat(attr, 0);
break;
case com.android.internal.R.styleable.TextAppearance_elegantTextHeight:
elegant = appearance.getBoolean(attr, false);
break;
case com.android.internal.R.styleable.TextAppearance_letterSpacing:
letterSpacing = appearance.getFloat(attr, 0);
break;
case com.android.internal.R.styleable.TextAppearance_fontFeatureSettings:
fontFeatureSettings = appearance.getString(attr);
break;
}
}
appearance.recycle();
兩個方式都可以完成。
這樣就完成了這個類,下面直接在Activity中使用。
需要是要在一個ListView中顯示,因此我們創建一個item 佈局:(添加一個自定義的命名空間shaixuan)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:shaixuan = "http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.canve.esh.view.shaixuanview.ShaiXuanItem
android:id="@+id/shaixuanItem"
shaixuan:itemTitle="默認1"
shaixuan:itemTitleColor="#ff8800"
shaixuan:itemTitleSize="18sp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
然後寫一下適配器(爲了快速實現,把假數據直接寫在類中了):
public class ShaiXuanListAdapter extends BaseAdapter {
private Context context;
public ShaiXuanListAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return 6;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.shaixuan_list_adapter_item_layout,parent,false);
ShaiXuanItem shaiXuanItem = (ShaiXuanItem) view.findViewById(R.id.shaixuanItem);//加載佈局,獲取剛纔的類對象
return view;
}
}
TesTActivity中的佈局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.canve.esh.activity.TestActivity"
>
<ListView
android:id="@+id/list_shaXuan1"
android:layout_below="@+id/grid_test"
android:layout_marginTop="15dp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
TesTActivity中的代碼:
public class TestActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "TestActivity";
private ItemAdapter itemAdapter;
private List<String> list;
private boolean isShow;
private ListView list_shaiXuan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
findViewById(R.id.btn_test).setOnClickListener(this);
list_shaiXuan = (ListView) findViewById(R.id.list_shaXuan1);
ShaiXuanListAdapter shaiXuanListAdapter = new ShaiXuanListAdapter(this);
list_shaiXuan.setAdapter(shaiXuanListAdapter);
}
}
完成了,此時的結果是:
我們重寫一下GridView 的onMeasure:
public class ExpandGridView extends GridView { public ExpandGridView(Context context) { super(context); } public ExpandGridView(Context context, AttributeSet attrs) { super(context, attrs); } public ExpandGridView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec( Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
然後ExpandGridView替換GridView後運行效果:
可以看到,這樣子就可以點擊展開了,基本實現了之前的需求。在此做一個簡單記錄,加深記憶。