做了很久的开发,看大别的大牛写的文章,知识分享,自己学的东西都很过时,老是赶不上发展的速度,哈哈出生晚呗!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后运行效果:
可以看到,这样子就可以点击展开了,基本实现了之前的需求。在此做一个简单记录,加深记忆。