提交 266c3671 编写于 作者: C Carson.Ho

具有搜索历史记录的搜索框

上级
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
Search_Layout
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
<entry name="!?*.form" />
<entry name="!?*.class" />
<entry name="!?*.groovy" />
<entry name="!?*.scala" />
<entry name="!?*.flex" />
<entry name="!?*.kt" />
<entry name="!?*.clj" />
<entry name="!?*.aj" />
</wildcardResourcePatterns>
<annotationProcessing>
<profile default="true" name="Default" enabled="false">
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
</component>
</project>
\ No newline at end of file
<component name="CopyrightManager">
<settings default="" />
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="$APPLICATION_HOME_DIR$/gradle/gradle-2.8" />
<option name="gradleJvm" value="1.8" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
<option name="myNullables">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
</list>
</value>
</option>
<option name="myNotNulls">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
</list>
</value>
</option>
</component>
<component name="ProjectInspectionProfilesVisibleTreeState">
<entry key="Project Default">
<profile-state>
<expanded-state>
<State>
<id />
</State>
</expanded-state>
<selected-state>
<State>
<id>Android</id>
</State>
</selected-state>
</profile-state>
</entry>
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
<component name="masterDetails">
<states>
<state key="ProjectJDKs.UI">
<settings>
<last-edited>1.8</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Search_Layout.iml" filepath="$PROJECT_DIR$/Search_Layout.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="" />
</component>
</project>
\ No newline at end of file
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "scut.carson_ho.search_layout"
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
}
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/Carson_Ho/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
package scut.carson_ho.search_layout;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="scut.carson_ho.search_layout">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
package scut.carson_ho.search_layout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
package scut.carson_ho.search_layout;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Carson_Ho on 16/11/15.
*/
//SQLiteOpenHelper子类用于打开数据库并进行对用户搜索历史记录进行增删减除的操作
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) {
//打开数据库,建立了一个叫records的表,里面只有一列name来存储历史记录:
db.execSQL("create table records(id integer primary key autoincrement,name varchar(200))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
package scut.carson_ho.search_layout;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* Created by Carson_Ho on 16/11/15.
*/
//解决ListView和ScrollView的冲突
public class Search_Listview extends ListView {
public Search_Listview(Context context) {
super(context);
}
public Search_Listview(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Search_Listview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
//通过复写其onMeasure方法、达到对ScrollView适配的效果
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
package scut.carson_ho.search_layout;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by Carson_Ho on 16/11/15.
*/
public class Search_View extends LinearLayout {
private Context context;
/*UI组件*/
private TextView tv_clear;
private EditText et_search;
private TextView tv_tip;
private ImageView iv_search;
/*列表及其适配器*/
private Search_Listview listView;
private BaseAdapter adapter;
/*数据库变量*/
private RecordSQLiteOpenHelper helper ;
private SQLiteDatabase db;
/*三个构造函数*/
//在构造函数里直接对搜索框进行初始化 - init()
public Search_View(Context context) {
super(context);
this.context = context;
init();
}
public Search_View(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
public Search_View(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
init();
}
/*初始化搜索框*/
private void init(){
//初始化UI组件
initView();
//实例化数据库SQLiteOpenHelper子类对象
helper = new RecordSQLiteOpenHelper(context);
// 第一次进入时查询所有的历史记录
queryData("");
//"清空搜索历史"按钮
tv_clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//清空数据库
deleteData();
queryData("");
}
});
//搜索框的文本变化实时监听
et_search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
//输入后调用该方法
@Override
public void afterTextChanged(Editable s) {
if (s.toString().trim().length() == 0) {
//若搜索框为空,则模糊搜索空字符,即显示所有的搜索历史
tv_tip.setText("搜索历史");
} else {
tv_tip.setText("搜索结果");
}
//每次输入后都查询数据库并显示
//根据输入的值去模糊查询数据库中有没有数据
String tempName = et_search.getText().toString();
queryData(tempName);
}
});
// 搜索框的键盘搜索键
// 点击回调
et_search.setOnKeyListener(new View.OnKeyListener() {// 输入完后按键盘上的搜索键
// 修改回车键功能
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
// 隐藏键盘,这里getCurrentFocus()需要传入Activity对象,如果实际不需要的话就不用隐藏键盘了,免得传入Activity对象,这里就先不实现了
// ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
// getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
boolean hasData = hasData(et_search.getText().toString().trim());
if (!hasData) {
insertData(et_search.getText().toString().trim());
queryData("");
}
//根据输入的内容模糊查询商品,并跳转到另一个界面,这个需要根据需求实现
Toast.makeText(context, "点击搜索", Toast.LENGTH_SHORT).show();
}
return false;
}
});
//列表监听
//即当用户点击搜索历史里的字段后,会直接将结果当作搜索字段进行搜索
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//获取到用户点击列表里的文字,并自动填充到搜索框内
TextView textView = (TextView) view.findViewById(android.R.id.text1);
String name = textView.getText().toString();
et_search.setText(name);
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
});
// // 插入数据,便于测试,否则第一次进入没有数据怎么测试呀?
// Date date = new Date();
// long time = date.getTime();
// insertData("Leo" + time);
//点击搜索按钮后的事件
iv_search.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean hasData = hasData(et_search.getText().toString().trim());
if (!hasData) {
insertData(et_search.getText().toString().trim());
//搜索后显示数据库里所有搜索历史是为了测试
queryData("");
}
//根据输入的内容模糊查询商品,并跳转到另一个界面,这个根据需求实现
Toast.makeText(context, "clicked!", Toast.LENGTH_SHORT).show();
}
});
}
/**
* 封装的函数
*/
/*初始化组件*/
private void initView(){
LayoutInflater.from(context).inflate(R.layout.search_layout,this);
et_search = (EditText) findViewById(R.id.et_search);
tv_clear = (TextView) findViewById(R.id.tv_clear);
tv_tip = (TextView) findViewById(R.id.tv_tip);
listView = (Search_Listview) findViewById(R.id.listView);
iv_search = (ImageView) findViewById(R.id.iv_search);
}
/*插入数据*/
private void insertData(String tempName) {
db = helper.getWritableDatabase();
db.execSQL("insert into records(name) values('" + tempName + "')");
db.close();
}
/*模糊查询数据 并显示在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(context, android.R.layout.simple_list_item_1, cursor, new String[] { "name" },
new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// 设置适配器
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
/*检查数据库中是否已经有该条记录*/
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 void deleteData() {
db = helper.getWritableDatabase();
db.execSQL("delete from records");
db.close();
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="scut.carson_ho.search_layout.MainActivity">
<scut.carson_ho.search_layout.Search_View
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/search_layout"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true"
android:orientation="vertical">