//流式布局
//先创建自定义view
public class CustomView extends ViewGroup {
int left=20;//左右的距离
int top=20;//上下的距离
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView(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 newleft=left;//给左右赋值
int newtop=top;//给上下赋值
//循环并且在下面判断宽度是否溢出 则溢出换行
for (int i=0;i<getChildCount();i++){
int measuredHeight = getChildAt(i).getMeasuredHeight();
int measuredWidth = getChildAt(i).getMeasuredWidth();
if(getChildAt(i).getVisibility()== View.GONE){
continue;
}if(measuredWidth+left+newleft>getWidth()){
newleft=20;
newtop=measuredHeight+top;
getChildAt(i).layout(newleft,newtop,newleft+measuredWidth,newtop+measuredHeight);
}else{
getChildAt(i).layout(newleft,newtop,newleft+measuredWidth,newtop+measuredHeight);
}
newleft+=measuredWidth+left;
}
}
}
//MyAcitity
//activity进行实现
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.Button_id);
final EditText editText = findViewById(R.id.EditText_id);
final CustomView c = findViewById(R.id.CustomView_id);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String trim = editText.getText().toString().trim();//得到输入框的内容
final TextView chen = new TextView(MainActivity.this);
chen.setText(trim);
c.addView(chen);
editText.setText(null);
chen.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
//长按隐藏 (本人偷懒当删除)
chen.setVisibility(View.GONE);
return true;
}
});
chen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s = chen.getText().toString();
editText.setText(s);
}
});
}
});
}
}
//布局
<?xml version="1.0" encoding="utf-8"?><LinearLayout
android:id="@+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/EditText_id"
android:layout_weight="20"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="请输入账号"
/>
<Button
android:id="@+id/Button_id"
android:layout_weight="5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="添加"
android:textSize="10sp"
/>
</LinearLayout>
<com.example.zidingyiview.CustomView
android:id="@+id/CustomView_id"
android:layout_below="@id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="200dp"></com.example.zidingyiview.CustomView>