效果图
主布局
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<EditText
android:id="@+id/edit"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="9"
android:hint="请输入搜索内容" />
<TextView
android:id="@+id/sousuo"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:text="搜索" />
</LinearLayout>
<com.bwie.month_liushibuju.custorm.CustormLiu
android:id="@+id/coustorm"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
自定义类
public class CustormLiu extends ViewGroup {
public CustormLiu(Context context) {
super(context);
}
public CustormLiu(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustormLiu(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@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 width = getWidth();
// 定义一个常量行数
int row = 0;
// 子控件左边的坐标
int disWidth = 18;
for (int i = 0; i < getChildCount(); i++) {
View view = getChildAt(i);
int viewWidth = view.getMeasuredWidth();
int viewHeight = view.getMeasuredHeight();
if (disWidth + viewHeight > width) {
row++;
disWidth = 18;
}
/*
view.layout(disWidth, row * viewHeight, viewWidth + disWidth, viewHeight * (row + 1));
disWidth += viewWidth;//disWidth = disWidth+viewWidth;
*/
view.layout(disWidth, row * viewHeight, viewWidth + disWidth, viewHeight * (row + 1));
disWidth += viewWidth;
}
}
}
主页面
public class MainActivity extends AppCompatActivity {
private EditText edit;
private TextView sousuo;
private CustormLiu coustorm;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
// 初始化控件
edit = findViewById(R.id.edit);
sousuo = findViewById(R.id.sousuo);
coustorm = findViewById(R.id.coustorm);
// 搜索点击事件
sousuo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView = new TextView(MainActivity.this);
// 获取输入框的值
String s = edit.getText().toString().trim();
textView.setText(s);
Log.i("cv","onclick:==="+s);
ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
coustorm.addView(textView,params);
Log.i("cv","onclick==="+textView);
Log.i("cv","onclick==="+params);
}
});
}
}