先创建一个View,继承ViewGroup ,实现里面的方法,创建onMeasure,用来获取宽高,再创建onLayout方法设置布局,然后只需要在展示的页面进行调用即可
public class AddDecreaseView extends ViewGroup {
public AddDecreaseView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//获取宽高
measureChildren(widthMeasureSpec,heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
//定义常量
int row = 0;
//定义宽度
int dwidth = 18;
//系统宽度
int width = getWidth();
//获取子控件数量
int childCount = getChildCount();
for (int i = 0; i <childCount ; i++) {
//获取布局
View childAt = getChildAt(i);
//获取布局的宽度
int measuredWidth = childAt.getMeasuredWidth();
//获取布局的高度
int measuredHeight = childAt.getMeasuredHeight();
//判断设置的宽度加上测量的宽度是否大于系统宽度
if(dwidth+measuredWidth>width){
//进行常量++
row++;
//设置宽度等于18
dwidth = 18;
}
//设置布局(定义宽度,布局的高度*常量,定义宽度+布局的宽度,(常量+1)*布局的高度)
childAt.layout(dwidth,measuredHeight*row,dwidth+measuredWidth,(row+1)*measuredHeight);
//定义的宽度+=系统的宽度
dwidth+=measuredWidth;
}
}
}
自定义View写完之后,在我们展示页面的布局进行调用,然后在展示页面进行操作,完成即可
//获取输入框
String s = editText.getText().toString().trim();
//新增TextView
final TextView textView = new TextView(MainActivity.this);
//设置边距
textView.setPadding(10,10,10,10);
/*//设置背景
textView.setBackgroundColor(R.drawable.shape);*/
//设置TextView
textView.setText(s);
//添加自定义View
ttt.addView(textView);