流失佈局 搜尋顯示 歷史記錄Listview顯示
阿新 • • 發佈:2019-01-26
====================MainActivity======================= public class MainActivity extends AppCompatActivity { private EditText etSearch; private TextView tvSearch; private Button btn_delete; private RecordSQLiteOpenHelper helper; private SimpleCursorAdapter adapter; privateSQLiteDatabase db; private ListView lvSearch; private FlowLayout flowLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化控制元件 etSearch = (EditText) findViewById(R.id.ed_search); tvSearch = (TextView) findViewById(R.id.tv_search); btn_delete = (Button) findViewById(R.id.btn_delete); lvSearch = (ListView) findViewById(R.id.lv_search); //初始化監聽 initListener(); //初始化資料 initData(); //流式佈局 initChildViews(); } //流式佈局 private voidinitChildViews() { flowLayout = (FlowLayout) findViewById(R.id.flow_layout); ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); lp.leftMargin = 5; lp.rightMargin = 5; lp.topMargin = 5; lp.bottomMargin = 5; for(int i = 0; i < datas.length; i ++){ TextView view = new TextView(this); view.setText(datas[i]); view.setTextColor(Color.WHITE); view.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_bg)); flowLayout.addView(view,lp); } } private void initListener() { //觸控框的監聽事件 etSearch.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { //點選輸入框顯示搜尋並獲取焦點 etSearch.setFocusable(true); etSearch.setFocusableInTouchMode(true); tvSearch.setVisibility(View.VISIBLE); return false; } }); tvSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 按完搜尋鍵後將當前查詢的關鍵字儲存起來,如果該關鍵字已經存在就不執行儲存 boolean hasData = hasData(etSearch.getText().toString().trim()); if (!hasData) { insertData(etSearch.getText().toString().trim()); queryData(""); } etSearch.setFocusable(false); etSearch.setFocusableInTouchMode(false); etSearch.clearFocus(); tvSearch.setVisibility(View.GONE); //跳轉到H5介面 String searchContent = etSearch.getText().toString().trim(); Toast.makeText(MainActivity.this, "搜尋內容為:"+searchContent, Toast.LENGTH_SHORT).show(); etSearch.setText(""); } }); //"清空搜尋歷史"按鈕 btn_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //清空資料庫 deleteData(); queryData(""); } }); } private void deleteData() { db = helper.getWritableDatabase(); db.execSQL("delete from records"); db.close(); } /*檢查資料庫中是否已經有該條記錄*/ private boolean hasData(String tempName) { //從Record這個表裡找到name=tempName的id Cursor cursor = helper.getReadableDatabase().rawQuery( "select id as _id,name from records where name =?", new String[]{tempName}); //判斷是否有下一個 return cursor.moveToNext(); } private String datas[] = { "羊毛衫 新品","碟子","蘋果8", "髕骨帶","胸罩","瑜伽球", }; private void initData() { //插入資料 initSearch(); //例項化資料庫SQLiteOpenHelper子類物件 helper = new RecordSQLiteOpenHelper(this); // 第一次進入時查詢所有的歷史記錄 queryData(""); } private void initSearch() { for (int i = 0; i < datas.length; i++) { final TextView textView = new TextView(this); textView.setText(datas[i]); //儲存按下能顯示selector的效果,需要設定一個如下的屬性 // textView.setBackground(DrawUtils.getSelector(DrawUtils.getDrawable(MainActivity.this, Color.rgb(210, 210, 210), DensityUtil.dip2px(this, 4)), DrawUtils.getDrawable(MainActivity.this, Color.WHITE, DensityUtil.dip2px(this, 4)))); //新增點選事件,也是實現顯示selector的效果的一種方式 textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //跳轉到H5介面 String searchContent = textView.getText().toString(); Toast.makeText(MainActivity.this, "" + searchContent, Toast.LENGTH_SHORT).show(); etSearch.setText(""); } }); } } /*模糊查詢資料 並顯示在ListView列表上*/ private void queryData(String tempName) { //模糊搜尋 Cursor cursor = helper.getReadableDatabase().rawQuery( "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null); // 建立adapter介面卡物件,裝入模糊搜尋的結果 adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"name"}, new int[]{android.R.id.text1}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); // 設定介面卡 lvSearch.setAdapter(adapter); adapter.notifyDataSetChanged(); } /*插入資料*/ private void insertData(String tempName) { db = helper.getWritableDatabase(); db.execSQL("insert into records(name) values('" + tempName + "')"); db.close(); } } ======================DrawUtils============================
package com.example.lenovo.zhoukao_01; /** * Created by lenovo on 2017/12/4. */ class DrawUtils { }======================FlowLayout===========================
/** * Created by lenovo on 2017/12/4. */ public class FlowLayout extends ViewGroup { //儲存所有子View private List<List<View>> mAllChildViews = new ArrayList<>(); //每一行的高度 private List<Integer> mLineHeight = new ArrayList<>(); public FlowLayout(Context context) { this(context, null);} public FlowLayout(Context context, AttributeSet attrs) { this(context, attrs, 0);} public FlowLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle);} @Override protected void onMeasure(int widthMeasureSpec, int 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 changed, int l, int t, int r, int b) {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; } } /** * 與當前ViewGroup對應的LayoutParams */ @Override public LayoutParams generateLayoutParams(AttributeSet attrs) {return new MarginLayoutParams(getContext(), attrs); } }================MyListView===================
public class MyListView extends ListView { public MyListView(Context context) { super(context); } public MyListView(Context context, AttributeSet attrs) { super(context, attrs); } public MyListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /** * 重新計算高度 * @param widthMeasureSpec * @param heightMeasureSpec */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }===================RecordSQLiteOpenHelper===================
public class RecordSQLiteOpenHelper extends SQLiteOpenHelper{ private static String name = "temp.db"; private static Integer version = 1; public RecordSQLiteOpenHelper(Context context) { super(context, name, null, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table records(id integer primary key autoincrement,name varchar(200))");
db.execSQL("insert into records(name) values('熱水器')");
} @Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { }}
====================drawable下的textview_bg.xml=======<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="5dp"/> <solid android:color="#999"/> <size android:height="10dp" android:width="10dp"/> </shape>===================activity_main===================
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="92px" android:gravity="center_vertical" android:focusable="true" android:padding="6px" android:focusableInTouchMode="true" android:orientation="horizontal"> <EditText android:layout_width="0dp" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:layout_margin="6px" android:layout_weight="1" android:focusable="false" android:focusableInTouchMode="false" android:hint="你好啊 我來啦 別跑啊" android:id="@+id/ed_search" android:paddingBottom="10px" android:paddingLeft="30px" android:paddingTop="10px" android:textColor="#333" android:textColorHint="#666" android:textSize="12sp"/> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/tv_search" android:text="搜尋" android:layout_marginRight="20px" android:layout_marginLeft="16px" android:gravity="center" android:textColor="#000fff" android:textSize="14sp"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:orientation="vertical" android:layout_height="wrap_content"> <TextViewandroid:layout_width="match_parent" android:layout_height="wrap_content" android:text="熱搜" android:padding="20px" android:textSize="36px"/>
<com.ljn.myapplication.FlowLayout android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/flow_layout"> </com.ljn.myapplication.FlowLayout></LinearLayout>
<LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"android:padding="20px">
<TextViewandroid:layout_width="wrap_content"android:layout_weight="0"android:layout_height="wrap_content"android:text="歷史搜尋"android:textSize="36px"/>
<com.ljn.myapplication.MyListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/lv_search"> </com.ljn.myapplication.MyListView></LinearLayout>
<Buttonandroid:layout_gravity="center"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="清空歷史搜尋"android:id="@+id/btn_delete"/>
</LinearLayout>
</ScrollView>