[关闭]
@MasterLeng 2015-07-09T14:51:32.000000Z 字数 7694 阅读 1522

模仿腾讯新闻首页搜索界面

数据库 android 本地存储

腾讯新闻最新版更新以后,在首页下拉后,会出现一个搜索栏,点击搜索栏后可以浏览历史记录(搜索内容存储到了本地数据库),并启动搜索。功能很简单,代码也不复杂:

*SearchActivity代码*

public class SearchActivity extends Actvity
{
//输入内容
private EditText editSearch;
//历史搜索列表
private SearchListView historySearch;
private ArrayAdapter adapter;
//清空历史记录
private Button btnClearHistory;
//取消
private Button btnCancel;
/**个人信息*/
SharedPreferences share;
String userId ="";
String mode;
String btnName;
int selectItem;
String selectState;
private DBHelper helper;
List list = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_helper_search);
share = getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
userId = share.getString("rowId", "");
mode = getIntent().getExtras().getString("mode");
btnName = getIntent().getExtras().getString("item");
selectItem = getIntent().getExtras().getInt("selectItem");
selectState = getIntent().getExtras().getString("all");
helper = DBHelper.getInstance(this);
initUI();
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
historySearch.setAdapter(adapter);
getHistoryFromDB();
}
//最好做成只显示十条的
public void getHistoryFromDB()
{
//历史搜索列表
List listHistory = new ArrayList();
SQLiteDatabase db = helper.getReadableDatabase();
//最多显示十条,并且倒序排列
Cursor cSearch = db.query(DBHelper.TABLE_NAME, new String[]{DBHelper.KEY_ID,DBHelper.KEY_SEARCH_CONTENT}, null, null, null, null, " _id desc", "10");
//循环取值
while (cSearch.moveToNext())
{
String searchContent=cSearch.getString(cSearch.getColumnIndexOrThrow(DBHelper.KEY_SEARCH_CONTENT));
listHistory.add(searchContent);
}
cSearch.close();
list.clear();
list.addAll(listHistory);
adapter.notifyDataSetChanged();
//历史记录大于1条,则显示清理按钮
if (list.size()>0) {
btnClearHistory.setVisibility(View.VISIBLE);
}
}
private void initUI()
{
editSearch = (EditText) findViewById(R.id.ns_et_keywords);
//点击搜索事件
editSearch.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
if (actionId==EditorInfo.IME_ACTION_SEARCH) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editSearch.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
Intent intent = new Intent();
//判断搜索内容是否为空
if (!TextUtils.isEmpty(v.getText().toString().trim())) {
intent.putExtra("search", v.getText().toString().trim());
intent.putExtra("mode", mode);
intent.putExtra("item", btnName);
intent.putExtra("selectItem", selectItem);
intent.putExtra("all", selectState);
//此处插入数据
SQLiteDatabase db = helper.getReadableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.KEY_SEARCH_CONTENT, v.getText().toString().trim());
db.insert(DBHelper.TABLE_NAME, null, cv);
intent.setClass(HelpSearchActivity.this, HelpCenterListActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.search_helper_in, R.anim.search_helper_out);
}
else
{
DialogUtil.showToast(HelpSearchActivity.this, "请输入搜索关键词");
}
return true;
}
return false;
}
});
//焦点移出EditText,收起键盘
editSearch.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
//EditText获取焦点,弹出键盘
final InputMethodManager im = (InputMethodManager) editSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (hasFocus) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
im.showSoftInput(editSearch, 0);
}
}, 500);
}
//失去焦点,收起键盘
else
{
im.hideSoftInputFromWindow(editSearch.getWindowToken(), 0);
}
}
});
historySearch = (SearchListView) findViewById(R.id.searchHistory);
btnClearHistory = (Button) findViewById(R.id.clearHistory);
final Handler handler = new Handler();
historySearch.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
// TODO Auto-generated method stub
final String content = (String)adapter.getItem(position);
editSearch.setText(content);
//延迟0.1秒
handler.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(HelpSearchActivity.this, HelpCenterListActivity.class);
intent.putExtra("search", content);
intent.putExtra("mode", mode);
intent.putExtra("item", btnName);
intent.putExtra("selectItem", selectItem);
intent.putExtra("all", selectState);
startActivity(intent);
overridePendingTransition(R.anim.search_helper_in, R.anim.search_helper_out);
}
}, 50);
}
});
btnClearHistory.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//删除历史记录
SQLiteDatabase db = helper.getReadableDatabase();
int deleteCount = db.delete(DBHelper.TABLE_NAME, null, null);
if (deleteCount>0) {
list.clear();
DialogUtil.showToast(HelpSearchActivity.this, "清理成功");
adapter.notifyDataSetChanged();
btnClearHistory.setVisibility(View.GONE);
}
}
});
btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
editSearch.clearFocus();
HelpSearchActivity.this.finish();
overridePendingTransition(R.anim.search_helper_in, R.anim.search_helper_out);
}
});
}
public static class DBHelper extends SQLiteOpenHelper
{
//数据库版本
public static final int DATABASE_VERSION = 1;
//数据库名称
public static final String DATABASE_NAME = "searchhistory.db";
//数据表名称
public static final String TABLE_NAME = "search";
//id列
public static final String KEY_ID = "_id";
//搜索记录的列
public static final String KEY_SEARCH_CONTENT = "search_content";
//建表语句
public static final String CREATE_TABLE = "create table "+TABLE_NAME
+" ("+KEY_ID+" integer primary key autoincrement,"+KEY_SEARCH_CONTENT+" TEXT);";
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
public static DBHelper getInstance(Context context)
{
return new DBHelper(context, DATABASE_NAME, null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
//表更新
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
if (oldVersion db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
}
}

SearchActivity布局文件

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

android:id="@+id/search_ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"

android:id="@+id/ns_et_keywords"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/search_bg"
android:layout_weight="1"
android:ems="10"
android:imeOptions="actionSearch"
android:singleLine="true"
android:hint="请输入关键词"
android:textColorHint="@color/ui_color_74"
android:textSize="14.5sp" />
android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="取消"
android:background="@drawable/search_btn"
/>

android:id="@+id/scroll"
android:layout_below="@+id/search_ll"
android:layout_height="wrap_content"
android:layout_width="match_parent"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
android:id="@+id/searchHistory"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" />
android:id="@+id/clearHistory"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="@+id/searchHistory"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:visibility="gone"
android:background="@drawable/btn_clear_history"
android:text="清空历史记录" />



`

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注