仅供参考:
外层布局:
//布局名为layout_liu <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/layout_liu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/layout_liu" android:gravity="center"> <Button android:id="@+id/deleteAll" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="清除历史记录" /> </LinearLayout> </RelativeLayout>
条目布局:
//布局名为text_liu <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/text_liu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/shap" android:padding="10dp" android:text="哈哈哈" /> </LinearLayout>
自定义view
public class FlowLayout extends LinearLayout { private LinearLayout layout_v; private Context context; private Button deleteAll; public FlowLayout(Context context) { super(context); initView(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } private void initView(Context context) { this.context = context; View view = LayoutInflater.from(context).inflate(R.layout.layout_liu, null, false); addView(view); layout_v = view.findViewById(R.id.layout_liu); deleteAll = view.findViewById(R.id.deleteAll); //清空历史记录按钮 deleteAll.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //清空布局内所有view layout_v.removeAllViews(); } }); } //等待调用,给集合即可 public void setList(List<String> list) { int len = 0; for (int i = 0; i < list.size(); i++) { //根据集合长度创建textview View view = View.inflate(context, R.layout.text_liu, null); TextView text = view.findViewById(R.id.text_liu); //修改当前TextView text.setText(list.get(i) + ""); Log.i("xxx", "setList: " + list.toString()); //添加给视图 layout_v.addView(view); //参数控制每一个TextView LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams(); layoutParams.rightMargin = 10; layoutParams.leftMargin = 10; layoutParams.topMargin = 10; layoutParams.weight = 1; view.setLayoutParams(layoutParams); } } }