自定义view
public class flowLayout extends ViewGroup{ public flowLayout(Context context) { this(context,null); } public flowLayout(Context context, AttributeSet attrs) { this(context,attrs,0); } public flowLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { //测量所有子view的宽高 measureChildren(0,0); int totalWidth = 0; int totalHeight = 0; //循环遍历所有的view for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); if (totalWidth + view.getMeasuredWidth() >= getMeasuredWidth()){ totalWidth = 0; totalHeight += view.getMeasuredHeight(); } view.layout(totalWidth, totalHeight, totalWidth+view.getMeasuredWidth(), totalHeight+view.getMeasuredHeight()); totalWidth += view.getMeasuredWidth(); } } }
activity
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group); flLayout = findViewById(R.id.flow_layout); edText = findViewById(R.id.ed_text); btnSearch = findViewById(R.id.btn_search); // for (int i = 0; i < 20; i++) { btnSearch.setOnClickListener(this); //} } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_search: txts = new TextView(this); result = edText.getText().toString(); ViewGroup.MarginLayoutParams layoutParams = new ViewGroup. MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); txts.setPadding(10, 10, 10, 10); layoutParams.setMargins(60, 20, 55, 20); txts.setLayoutParams(layoutParams); txts.setText(result); txts.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { flLayout.removeView(txts); } }); flLayout.addView(txts); } } }
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.windows.month1025.GroupActivity"> <LinearLayout android:padding="20dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <EditText android:id="@+id/ed_text" android:layout_weight="3" android:layout_width="0dp" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_search" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:text="搜索"/> </LinearLayout> <com.example.windows.month1025.display.flowLayout android:id="@+id/flow_layout" android:layout_marginTop="20dp" android:layout_width="match_parent" android:layout_height="wrap_content"></com.example.windows.month1025.display.flowLayout> </LinearLayout>