在这章我,我们将通过自定义的一个ViewGroup来实现一个类似于今日头条中编辑分类添加的效果。
首先,需要先继承一个ViewGroup。
public class MyViewGroup extends ViewGroup{
public MyViewGroup(Context context,AttributeSet attrs) {
super(context);
// TODO Auto-generated constructor stub
addView(CreatView());
}
}
因为在这个group中可以添加新的子view,所有需要对view的大小左处理
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
// int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
// int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
// int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
int childCount = getChildCount();
Log.d("HK", "childCount = "+childCount);
if(childCount == 0) {
setMeasuredDimension(0, 0);
Log.d("HK", "setMeasuredDimension(0, 0)");
} else {
Log.d("HK", "setMeasuredDimension(chirldWidth, chirldHight)");
for(int i=0;i<childCount;i++) {
TextView tvChild = (TextView) getChildAt(i);
measureChild(tvChild, widthMeasureSpec, heightMeasureSpec);
int childWidth = tvChild.getMeasuredWidth();
int childHight = tvChild.getMeasuredHeight();
int row = i-1/4;
Log.d("HK", "childWitch = "+childWidth);
setMeasuredDimension(childWidth*4, (childHight)*(row+1));
Log.d("HK", "setMeasuredDimension w h = "+childWidth*4+" "+childHight*(row+1));
}
}
}
这面通过多次Measure子view的高和宽来设置viewGroup的高宽,此处保证每行4个,超过4个则添加一行。在设置好viewGroup后,接下来就需要将子View安放在里面。
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
int childCount = getChildCount();
int left = 0;
//int row = childCount/4;
int mod = childCount%4;
int row = 0;
TextView childView;
for(int i=0;i<childCount;i++) {
childView = (TextView) getChildAt(i);
if(i==childCount-1) {
//给最后一个子view添加点击事件,通过点击可以新建一个子view
childView.setText("点击添加");
childView.setBackgroundColor(Color.BLUE);
childView.setTextColor(Color.BLACK);
childView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("HK", "onLayout Click");
addView(CreatView());
//requestLayout();
invalidate();
}
});
} else {
childView.setText("新加入的");
childView.setTextColor(Color.BLACK);
childView.setBackgroundColor(Color.GREEN);
}
int width = childView.getMeasuredWidth();
Log.d("HK", "onLayout = "+width+" "+childView.getHeight());
row = i/4;
if((i+1)%4==1&&row!=0) {
left = 0;
Log.d("HK", "onLayout change line");
}
childView.layout(left, childView.getMeasuredHeight()*row, left+width, childView.getMeasuredHeight()*(row+1));
Log.d("HK", "childView.layout left top right buttom= "+left+" "+0+" "+(left+width)+" "+childView.getMeasuredHeight());
left += width;
Log.d("HK", "onLayout row = "+row +" "+i%4+" "+i);
}
}
//新建子view的方法
protected TextView CreatView() {
TextView tv = new TextView(MyContext.getContext());
tv.setHeight(80);
tv.setWidth(220);
return tv;
}
详细代码请见github
GITHUB:https://github.com/everyhappy/myViews