流式布局 + 添加数据库的小demo

本文介绍了一种自定义的流式布局控件Liushi,该控件继承自ViewGroup,能够实现类似流式布局的效果,同时展示了如何在Android应用中使用此控件并结合数据库操作来动态展示和管理数据。

这个自定义的控件他就要继承一个ViewGroup 下面就是自定义的控件

public class Liushi extends ViewGroup {

    //存储所有子View
    private List<List<View>> mAllChildViews = new ArrayList<>();
    //每一行的高度
    private List<Integer> mLineHeight = new ArrayList<>();

    public Liushi(Context context) {
        super(context);
    }

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //父控件传进来的宽度和高度以及对应的测量模式
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        //如果当前ViewGroup的宽高为wrap_content的情况
        int width = 0;//自己测量的 宽度
        int height = 0;//自己测量的高度
        //记录每一行的宽度和高度
        int lineWidth = 0;
        int lineHeight = 0;

        //获取子view的个数
        int childCount = getChildCount();
        for(int i = 0;i < childCount; i ++){
            View child = getChildAt(i);
            //测量子View的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            //得到LayoutParams
            MarginLayoutParams lp = (MarginLayoutParams) getLayoutParams();
            //子View占据的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            //子View占据的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
            //换行时候
            if(lineWidth + childWidth > sizeWidth){
                //对比得到最大的宽度
                width = Math.max(width, lineWidth);
                //重置lineWidth
                lineWidth = childWidth;
                //记录行高
                height += lineHeight;
                lineHeight = childHeight;
            }else{//不换行情况
                //叠加行宽
                lineWidth += childWidth;
                //得到最大行高
                lineHeight = Math.max(lineHeight, childHeight);
            }
            //处理最后一个子View的情况
            if(i == childCount -1){
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }
        }
        //wrap_content
        setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,
                modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean b, int l, int i1, int i2, int i3) {
        mAllChildViews.clear();
        mLineHeight.clear();
        //获取当前ViewGroup的宽度
        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;
        //记录当前行的view
        List<View> lineViews = new ArrayList<View>();
        int childCount = getChildCount();
        for(int i = 0;i < childCount; i ++){
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            //如果需要换行
            if(childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width){
                //记录LineHeight
                mLineHeight.add(lineHeight);
                //记录当前行的Views
                mAllChildViews.add(lineViews);
                //重置行的宽高
                lineWidth = 0;
                lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
                //重置view的集合
                lineViews = new ArrayList();
            }
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
            lineViews.add(child);
        }
        //处理最后一行
        mLineHeight.add(lineHeight);
        mAllChildViews.add(lineViews);

        //设置子View的位置
        int left = 0;
        int top = 0;
        //获取行数
        int lineCount = mAllChildViews.size();
        for(int i = 0; i < lineCount; i ++){
            //当前行的views和高度
            lineViews = mAllChildViews.get(i);
            lineHeight = mLineHeight.get(i);
            for(int j = 0; j < lineViews.size(); j ++){
                View child = lineViews.get(j);
                //判断是否显示
                if(child.getVisibility() == View.GONE){
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                int cLeft = left + lp.leftMargin;
                int cTop = top + lp.topMargin;
                int cRight = cLeft + child.getMeasuredWidth();
                int cBottom = cTop + child.getMeasuredHeight();
                //进行子View进行布局
                child.layout(cLeft, cTop, cRight, cBottom);
                left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            }
            left = 0;
            top += lineHeight;
        }
    }
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        // TODO Auto-generated method stub

        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                //Toast.makeText(getContext(),mAllChildViews.toString(), Toast.LENGTH_SHORT).show();
 break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return true;
    }
}

// 下面就要来写一个main布局

<?xml version="1.0" encoding="utf-8"?>
<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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <ImageView
            android:id="@+id/back_sousuo"
            android:layout_width="20dp"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:src="@mipmap/icon_back"
            android:layout_marginLeft="10dp"/>

        <EditText
            android:layout_marginLeft="10dp"
            android:layout_weight="3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:id="@+id/name"
            android:hint="最新上市,内衣三免一,服装免费送秩序1分钱"
            />
        <Button
            android:onClick="add"
            android:layout_marginLeft="10dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="搜索"
            android:layout_gravity="center" />
    </LinearLayout>

    <com.example.hasee.guojiaxingjingddongdemo.shujuku.Liushi
        android:id="@+id/ls"
        android:layout_width="match_parent"
        android:layout_height="80dp"></com.example.hasee.guojiaxingjingddongdemo.shujuku.Liushi>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="历史记录"
        android:textSize="24dp"
        />


    <ListView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/lv"></ListView>

    <Button
        android:onClick="delall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="清空历史记录"
        android:layout_gravity="center"
        android:gravity="center"
        android:visibility="invisible"
        android:id="@+id/btn"/>
</LinearLayout>

//下面就是主Activity的代码了

public class LiushiActivity extends AppCompatActivity {

    private ImageView back;
    private EditText name_ed;
    private ListView lv;
    private Dao dao;
    private List<String> sel;
    private ArrayAdapter<String> adapter;
    private Button btn;
    private Liushi mFlowLayout;
    List<String> a=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_liushi);
        name_ed = findViewById(R.id.name);
        back = findViewById(R.id.back_sousuo);
        btn = findViewById(R.id.btn);
        lv = findViewById(R.id.lv);
        mFlowLayout= findViewById(R.id.ls);
        dao = new Dao(LiushiActivity.this);
        sel = dao.sel();
        adapter = new ArrayAdapter<>(LiushiActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, sel);
        lv.setAdapter(adapter);

        if (sel.size()>0){
            btn.setVisibility(View.VISIBLE);
        }else if (sel.size()==0){
            btn.setVisibility(View.INVISIBLE);
        }
        initChildViews();


        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LiushiActivity.this,MainActivity.class);
                startActivity(intent);
            }
        });
    }


    private void zhanshi() {
        List<String> sel4 = dao.sel();
        ArrayAdapter<String> ada = new ArrayAdapter<>(LiushiActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, sel4);
        lv.setAdapter(ada);
    }


    private String mNames[] = {
            "外套","夹克","皮鞋",
            "耐克","女鞋","阿迪达斯",
            "name","type","search","logcat",

    };
    private void initChildViews() {
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 10;
        lp.rightMargin = 10;
        lp.topMargin = 5;
        lp.bottomMargin = 5;
        for (int i = 0; i < mNames.length; i++) {
            TextView view = new TextView(this);
            view.setText(mNames[i]);
            view.setTextColor(Color.WHITE);

            final int finalI = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(LiushiActivity.this,mNames[finalI], Toast.LENGTH_SHORT).show();
                }
            });

            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_bg));
            mFlowLayout.addView(view, lp);


        }
    }


    public void add(View view) {
        String name = name_ed.getText().toString();
        int i = dao.insertJson(name);btn.setVisibility(View.VISIBLE); List<String> sel3 = dao.sel();
        a.add(0,name);
        ArrayAdapter<String> adapter3 = new ArrayAdapter<>(LiushiActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, a);
        lv.setAdapter(adapter3);
        Intent it1 = new Intent(this,SousuoActivity.class);
        it1.putExtra("name",name);
        startActivity(it1);
    }

    public void delall(View view) {
        dao.del();
        List<String> sel2 = dao.sel();
        ArrayAdapter<String> adapter2 = new ArrayAdapter<>(LiushiActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, sel2);

        lv.setAdapter(adapter2);

        Toast.makeText(LiushiActivity.this,"清除成功",Toast.LENGTH_LONG).show();

        btn.setVisibility(View.INVISIBLE);
    }
}

//剩下就要写 创建数据库了

public class Myhelpher extends SQLiteOpenHelper {
    public Myhelpher(Context context) {
        super(context, "sss.db", null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //创建表
        sqLiteDatabase.execSQL("create table shuju1(id integer primary key autoincrement,json text not null)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

// 对数据库进行操作

public class Dao {

    private final Myhelpher myhelpher;
    private SQLiteDatabase d;
    private SQLiteDatabase db;

    public Dao(Context context) {
        myhelpher = new Myhelpher(context);
    }
    public int insertJson(String json){
        SQLiteDatabase database = myhelpher.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("json",json);
        database.insert("shuju1",null,values);
        //关闭
        database.close();
        return 1;
    }
    public List<String> sel(){
        d = myhelpher.getReadableDatabase();

        List<String> list=new ArrayList<>();
        Cursor cursor = d.rawQuery("select * from shuju1", null);

        while (cursor.moveToNext()){
            String s = cursor.getString(1);
            list.add(s);
        }
        return list;
    }
    public void del(){
        db = myhelpher.getWritableDatabase();
        db.execSQL("delete from shuju1");


    }
    public int delyi(String i) {
        db = myhelpher.getWritableDatabase();
        db.execSQL("delete from shuju1 where json=?", new String[]{i});

        return 1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值