Android自定义流式布局(搜索历史记录)

仅供参考:

外层布局:

//布局名为layout_liu


    

    

    

        

条目布局:

//布局名为text_liu


    


自定义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 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);
        }

    }

}

 

你可能感兴趣的:(Android)