流式布局 FlowView

思路分析:1、首先要写一个Xml文件代表属性
2、开始写流式布局类 继承于LinearLayout
3一、首先获取系统屏幕的宽度
二、初始化LinearLayout 、初始化TextView
三、设置数据
①计算LinearLayout能得到多少个子控件 (for循环计算一行子控件的宽的和)
②通过下标得到每个子控件,然后测量宽高
③如果系统屏幕宽度大于LinearLayout+数据的宽度才能添加,否则要换行重新初始化LinearLayout布局
④考虑字符串过长的时候要进行截取重新测量字符串宽度

首先引用自定义TitleView组件
values下的attrs文件

<?xml version="1.0" encoding="utf-8"?>

activity_mian 文件

<?xml version="1.0" encoding="utf-8"?>

<com.example.week1.view.TitleView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/titleView"/>
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="搜索历史"
        android:layout_marginLeft="10dp"/>

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:id="@+id/Delete_Text"
        android:text="删除"
        android:layout_marginRight="10dp"
        android:layout_alignParentRight="true"/>

</RelativeLayout>

<com.example.week1.view.FlowView
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:id="@+id/MyFloat_Layout_History"
    app:textColor="@color/colorPrimaryDark"
    />

<TextView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="热门搜索"
    android:layout_marginLeft="10dp"/>
<com.example.week1.view.FlowView
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:id="@+id/MyFloat_Layout"
    app:textColor="@color/colorPrimaryDark"
    />
TtileView类 public class TitleView extends LinearLayout {
private  EditText edit;
private  TextView textView_add;

public TitleView(Context context, AttributeSet attrs) {
    super(context, attrs);
   LayoutInflater.from(context).inflate(R.layout.title,this);
    edit = findViewById(R.id.Search_Edit);
    textView_add= findViewById(R.id.add);
}

public String getEdit() {
    return edit.getText().toString().trim();
}

public TextView getTextView_add() {
    return textView_add;
}

}
FlowView类
public class FlowView extends LinearLayout {
private int mScreenWidth;
private int mScreenHeight;
private String mColor;
public FlowView(Context context, AttributeSet attrs) {
super(context, attrs);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
mScreenWidth = metrics.widthPixels;
mScreenHeight = metrics.heightPixels;
//设置这个布局垂直显示
setOrientation(VERTICAL);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.GroupDemoView);
if (typedArray != null) {
mColor = (String) typedArray.getText(R.styleable.GroupDemoView_textColor);
}

}

public void removeChildView() {
    //移除所有子控件
    removeAllViews();
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
}

public void setData(ArrayList<String> data) {
    LinearLayout linearLayout = getLin();//[lvxx,lxs,lzs,lzzs]
    for (int i = 0; i < data.size(); i++) {//lvxx
        final String tmp = data.get(i);
        int numWidth = 0;
        //得到一行LinearLayout到底有多少子控件  因为我要计算每个子控件加在一起的宽度
        int childCount = linearLayout.getChildCount();
        //这个for循环只是计算一行LinearLayout的所有子控件的宽的和
        for (int j = 0; j < childCount; j++) {
            //通过index得到每一个子控件
            TextView tv = (TextView) linearLayout.getChildAt(j);
            LayoutParams layoutParams = (LayoutParams) tv.getLayoutParams();
            int leftMargin = layoutParams.leftMargin;
            //测量这个tv的高和宽
            tv.measure(getMeasuredWidth(), getMeasuredHeight());
            numWidth += tv.getMeasuredWidth() + leftMargin + tv.getPaddingLeft() + getPaddingRight();
        }

        TextView dataText = getText();
       /* dataText.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), tmp, Toast.LENGTH_SHORT).show();
            }
        });*/
        //设置属性
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.leftMargin = 15;
        params.topMargin = 10;
        dataText.setLayoutParams(params);
        dataText.setText(tmp);
        dataText.measure(getMeasuredWidth(), getMeasuredHeight());
        int dataTextWidth = dataText.getMeasuredWidth() + dataText.getPaddingLeft() + dataText.getPaddingRight();
        //考虑到一个字符串很长 就直接超过整个屏幕的高了
        if (dataTextWidth>=mScreenWidth){
            String s = tmp.substring(0, 4);
         dataText.setText(s+"...");
           dataText.measure(getMeasuredWidth(), getMeasuredHeight());
           dataTextWidth = dataText.getMeasuredWidth();
       }

        if (mScreenWidth >= numWidth + dataTextWidth) {//lvxx
            linearLayout.addView(dataText);
        } else {
            //这里面对LinearLayout重新赋值  通过getLin换行
            linearLayout = getLin();
            linearLayout.addView(dataText);
        }

    }

}

//初始化子LinearLayout

private LinearLayout getLin() {
    LinearLayout linearLayout = new LinearLayout(getContext());
    //LayoutParams 控制组件大小的一个工具类
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    linearLayout.setLayoutParams(params);
    //this本类对象
    this.addView(linearLayout);//只要重新添加View了自动换行了
    return linearLayout;
}

//初始化TextView
private TextView getText() {
    TextView textView = new TextView(getContext());
    textView.setTextSize(20);
    textView.setTextColor(Color.parseColor(mColor));
    textView.setBackgroundResource(R.drawable.text_style);
    textView.setPadding(10, 3, 10, 3);
    return textView;
}

}
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private String[] data = new String[]{"达利园", "旺旺小小酥旺旺小小酥旺旺小小酥旺旺小小酥旺旺小小酥旺旺小小酥旺旺小小酥旺旺小小酥旺旺小小酥旺旺小小酥旺旺小小酥旺旺小小酥旺旺小小酥", "牛奶面包", "香蕉苹果", "奥利奥", "达利园", "旺旺小小酥", "牛奶面包", "香蕉苹果", "奥利奥", "达利园"};
private MyDao mDao;
private ArrayList<String> mList = new ArrayList<>();
private ArrayList<String> mHistory = new ArrayList<>();
private TextView mDelete;
private FlowView MyFloat_Layout;
private FlowView History_Layout;
private TitleView titleView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDao = new MyDao(this);
    mHistory = mDao.selectName();
    initData();
    initViews();
    if (!mHistory.isEmpty()) {
    History_Layout.setData(mHistory);
    }
}
private void initData() {
    for (int i = 0; i < data.length; i++) {
        mList.add(data[i]);
    }
}
private void initViews() {
    mDelete = findViewById(R.id.Delete_Text);
    mDelete.setOnClickListener(this);
    MyFloat_Layout = findViewById(R.id.MyFloat_Layout);
    MyFloat_Layout.setData(mList);
    History_Layout = findViewById(R.id.MyFloat_Layout_History);
    titleView = findViewById(R.id.titleView);
    titleView.getTextView_add().setOnClickListener(this);
}
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.add:

            String sname = titleView.getEdit().trim();
          /*  *//*Toast.makeText(MainActivity.this,sname.toString(),Toast.LENGTH_LONG).*//*show();*/
            //自己封装了一个方法删除子控件
            History_Layout.removeChildView();
            mHistory.add(sname);
            mDao.insertSqlite(sname);
               Toast.makeText(this, "插入成功", Toast.LENGTH_SHORT).show();
            History_Layout.setData(mHistory);
            break;
        case R.id.Delete_Text:
            mDao.delete();
            History_Layout.removeChildView();
            break;
    }
}

}
数据库Dao层
public class MyDao {

private final SQLiteDatabase sd;
private Context context;

public MyDao(Context context){
    MyHelper myHelper = new MyHelper(context);
    sd = myHelper.getWritableDatabase();
}


//插入
public void insertSqlite(String name){
    ContentValues contentValues = new ContentValues();
    contentValues.put("name", name);
    sd.insert("shops", null, contentValues);

}
//查询
public ArrayList<String> selectName(){
    ArrayList<String> list = new ArrayList<>();
    Cursor cursor = sd.query("shops", null, null, null, null, null, null);
    while (cursor.moveToNext()){
        String sname = cursor.getString(cursor.getColumnIndex("name"));
        list.add(sname);
    }
    return list;
}
//删除
public void delete(){
    sd.delete("shops",null,null);
}

}

猜你喜欢

转载自blog.csdn.net/weixin_43629061/article/details/84726685