流式布局简单实现

//主方法

//创建集合
	private List<String> mStrings=new ArrayList<>();
	
	
   final EditText ed_search=(EditText)findViewById(R.id.ed_search);
        ed_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = ed_search.getText().toString().trim();
                if (TextUtils.isEmpty(trim)) {
                    Toast.makeText(getContext(),"请输入内容",Toast.LENGTH_SHORT).show();
                    return;
                }
                mStrings.add(trim);
                goodView.setList(mStrings);
            }
        });

//自定义布局GoodView

public class GoodView extends RelativeLayout {

    private LinearLayout view_v;
    private LinearLayout view_h;

    public GoodView(Context context) {
        super(context);
        init(context);
    }

    public GoodView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public GoodView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private Context context;
    private void init(Context context) {
        this.context=context;
        view_v =(LinearLayout) View.inflate(context, R.layout.goodview_v, null);
        addView(view_v);
    }

    public void setList(List<String> datas) {

        view_v.removeAllViews();
        view_h = (LinearLayout)View.inflate(context, R.layout.goodview_h, null);
        view_v.addView(view_h);

        view_h.removeAllViews();
        int len=0;
        for (int i=0;i<datas.size();i++){
            String s = datas.get(i);
            len+=s.length();
            if (len>22) {
                //转行
                view_h = (LinearLayout)View.inflate(context, R.layout.goodview_h, null);
                view_v.addView(view_h);
                len=0;
            }


            View view_text = View.inflate(context, R.layout.goodview_text, null);
            TextView tv_text=view_text.findViewById(R.id.tv_text);
            tv_text.setText(datas.get(i));
            view_h.addView(view_text);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view_text.getLayoutParams();
            layoutParams.weight=1;
            view_text.setLayoutParams(layoutParams);
        }

    }
}


猜你喜欢

转载自blog.csdn.net/Guilin666/article/details/83312716