安卓 搜索页面

1.添加依赖

implementation 'com.hyman:flowlayout-lib:1.1.2'

2.activity

public class SearchActivity extends AppCompatActivity  {

    @BindView(R.id.input_search_content_et)
    ClearEditText inputSearchContentEt;
    @BindView(R.id.search_content_cancel_tv)
    TextView searchContentCancelTv;
    @BindView(R.id.tv_history)
    TextView tvHistory;
    @BindView(R.id.image_clear)
    ImageView imageClear;
//    @BindView(R.id.search_content_show_ll)
//    LinearLayout searchContentShowLl;
    @BindView(R.id.list_search)
    ListView listSearch;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.rl_caozuo)
    RelativeLayout rlCaozuo;
    @BindView(R.id.iv_black)
    ImageView ivBlack;
    @BindView(R.id.id_flowlayout)
    TagFlowLayout idFlowlayout;
    private SearchRecordsAdapter recordsAdapter;
    private List searchRecordsList;
    private List tempList;
    private RecordsDao recordsDao;
    private AlertDialog.Builder builder;
    private String uuid,token;
    private ProgressDialog progressDialog;
    private List shipinlist = new ArrayList<>();
    private ShiPinListAdapter shipinadapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        initData();
        bindAdapter();
        initListener();
    }
    public void xianshi(String string){
     inputSearchContentEt.setText(string);
    }




    private void initData() {
        recordsDao = new RecordsDao(this);
        searchRecordsList = new ArrayList<>();
        tempList = new ArrayList<>();
        tempList.addAll(recordsDao.getRecordsList());

        reversedList();
        //第一次进入判断数据库中是否有历史记录,没有则不显示
        checkRecordsSize();
    }


    private void bindAdapter() {
//list转化数组
        String[] array = searchRecordsList.toArray(new String[0]);
        idFlowlayout.setAdapter(new TagAdapter(array) {


            @Override
            public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, String s) {
                final LayoutInflater mInflater = LayoutInflater.from(SearchActivity.this);
                TextView tv = (TextView) mInflater.inflate(R.layout.tv_tag,
                        idFlowlayout, false);
                tv.setText(s);
                return tv;
            }

            //             为标签设置预点击内容(就是一开始就处于点击状态的标签)
            @Override
            public boolean setSelected(int position, String s) {
                return false;
            }
        });
//          为点击标签设置点击事件.
        idFlowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, com.zhy.view.flowlayout.FlowLayout parent) {
                inputSearchContentEt.setText(searchRecordsList.get(position));
                return false;
            }

        });
    }

    private void initListener() {
        searchContentCancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String record = inputSearchContentEt.getText().toString();
                recordsDao.addRecords(record);
                String tempName = inputSearchContentEt.getText().toString();
                tempList.clear();
                tempList.addAll(recordsDao.querySimlarRecord(tempName));
                reversedList();
                checkRecordsSize();
                llSearch.setVisibility(View.VISIBLE);
                rlCaozuo.setVisibility(View.GONE);
                idFlowlayout.setVisibility(View.GONE);
                setTvShipin();
               bindAdapter();

            }
        });
        ivBlack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        imageClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTwo();
            }
        });
    }

    //当没有匹配的搜索数据的时候不显示历史记录栏
    private void checkRecordsSize() {
    }


    private void showTwo() {
        android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(SearchActivity.this)
                .setTitle("清除历史记录")
                .setMessage("是否要清除历史记录")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO: 2018/4/16 positive
                        tempList.clear();
                        reversedList();
                        recordsDao.deleteAllRecords();
                        bindAdapter();
//                        searchRecordsLl.setVisibility(View.GONE);
                        inputSearchContentEt.setHint("请输入你要搜索的内容");

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO: 2018/4/16 negative
                    }
                }).create();
        alertDialog.show();
        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(Color.GRAY);
        alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.RED);
    }
    private void setTvShipin() {
        SharedPreferences sPreferences = getSharedPreferences("Login", MODE_PRIVATE);
        token = sPreferences.getString("token", "");
        uuid= sPreferences.getString("userid", "");
        OkGo.get(url).headers("authorization", token).execute(new StringCallback() {
            @Override
            public void onSuccess(Response response) {
                ShiPinLieBiaoModel shouYeXiaoXiModel = new ShiPinLieBiaoModel();
                shouYeXiaoXiModel = new Gson().fromJson(response.body().toString(), ShiPinLieBiaoModel.class);
                Log.w("11111", response.body().toString());
                if (shouYeXiaoXiModel.getCode() == 1) {

                    shipinlist = (List) shouYeXiaoXiModel.getData();
//                    Log.e("条数", shipinlist.size() + "");
//                    shipinlist1.addAll(shipinlist);
                    if (response.body().contains("暂无数据")) {
                        Toast.makeText(SearchActivity.this, shouYeXiaoXiModel.getMsg(), Toast.LENGTH_SHORT).show();
                    } else {

                        shipinadapter = new ShiPinListAdapter(SearchActivity.this, R.layout.item_shipin, shipinlist);
                        listSearch.setAdapter(shipinadapter);
                    }
                }

            }
        });
    }

    //颠倒list顺序,用户输入的信息会从上依次往下显示
    private void reversedList() {
        searchRecordsList.clear();
        for (int i = tempList.size() - 1; i >= 0; i--) {
            searchRecordsList.add(tempList.get(i));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (inputSearchContentEt.getText().length() == 0) {
            llSousuojieguo.setVisibility(View.GONE);
            rlCaozuo.setVisibility(View.VISIBLE);
          bindAdapter();
        }
    }

}
3.操作类
public class RecordsDao {
        RecordSQLiteOpenHelper recordHelper;

    SQLiteDatabase recordsDb;

public RecordsDao(Context context) {
        recordHelper = new RecordSQLiteOpenHelper(context);
        }

//添加搜索记录
public void addRecords(String record) {

        if (!isHasRecord(record)) {
        recordsDb = recordHelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", record);
        //添加
        recordsDb.insert("records", null, values);
        //关闭
        recordsDb.close();
        }
        }

//判断是否含有该搜索记录
public boolean isHasRecord(String record) {
        boolean isHasRecord = false;
        recordsDb = recordHelper.getReadableDatabase();
        Cursor cursor = recordsDb.query("records", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
        if (record.equals(cursor.getString(cursor.getColumnIndexOrThrow("name")))) {
        isHasRecord = true;
        }
        }
        //关闭数据库
        recordsDb.close();
        cursor.close();
        return isHasRecord;
        }

//获取全部搜索记录
public List getRecordsList() {
        List recordsList = new ArrayList<>();
        recordsDb = recordHelper.getReadableDatabase();
        Cursor cursor = recordsDb.query("records", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
        String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
        recordsList.add(name);
        }
        //关闭数据库
        recordsDb.close();
        cursor.close();
        return recordsList;
        }

//模糊查询
public List querySimlarRecord(String record){
        String queryStr = "select * from records where name like '%" + record + "%' order by name ";
        List similarRecords = new ArrayList<>();
        Cursor cursor= recordHelper.getReadableDatabase().rawQuery(queryStr,null);

        while (cursor.moveToNext()) {
        String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
        similarRecords.add(name);
        }

        cursor.close();
        return similarRecords;
        }

//清空搜索记录
public void deleteAllRecords() {
        recordsDb = recordHelper.getWritableDatabase();
        recordsDb.execSQL("delete from records");

        recordsDb.close();
        }
// 删除
public int delete(int _id) {

        SQLiteDatabase db = recordHelper.getWritableDatabase();
        int d = db.delete("records", "_id=?", new String[] { _id + "" });

        db.close();
        return d;

        }



}

4.帮助类

public class RecordSQLiteOpenHelper extends SQLiteOpenHelper {

    private final static String DB_NAME = "temp.db";
    private final static int DB_VERSION = 10;

    public RecordSQLiteOpenHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sqlStr = "CREATE TABLE IF NOT EXISTS records (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);";
        db.execSQL(sqlStr);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }


}

5.搜索页面布局

 



    
        
        
            
            
        

        

    

    

        

        
    

    






        



    

    
        

    

你可能感兴趣的:(安卓 搜索页面)