private static final int MENU_SEARCH = 1;
// @Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_SEARCH, 0, R.string.menu_search).setIcon(
android.R.drawable.ic_search_category_default)
.setAlphabeticShortcut(SearchManager.MENU_KEY);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SEARCH:
// 点击菜单时,显示查询Box,等待用户输入
ed.setText("");
ed.setVisibility(View.VISIBLE);
return true;
}
return super.onOptionsItemSelected(item);
}
布局 xml 文档内容:
android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> android:layout_height="wrap_content" android:layout_width="fill_parent" android:hint="Search" > android:layout_width="fill_parent" android:layout_height="wrap_content" /> android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="没有安排" android:textSize="25sp" android:gravity="center_vertical|center_horizontal" android:visibility="gone" />
ed = (EditText) findViewById(R.id.EditText01);
// 初始化 EditText 时,不显示该 View ,注意其 Visibility 为 View.GONE ,而不是 View.INVISIBILITY ,区别是前者不会占用显示区域,而后者会占用显示区域,即使不显示,其所在位置也为空白,而前者不会
ed.setVisibility(View.GONE);
ed.setText("");
eventsListView = (ListView) findViewById(R.id.view_all_my_day_list);
// 为 EditText 增加文本改变的监听器
TextWatcher edWatch = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (dayEventsList != null && dayEventsList.size() > 0) {
String searchTxt = ed.getText().toString();
// 实时改变 ListView 的数据
searchBindDataToView(queryEventsList(searchTxt));
}
}
};
ed.addTextChangedListener(edWatch);
// 当再次显示该 Activity 时,隐藏 EditText
@Override
protected void onRestart() {
super.onRestart();
ed.setVisibility(View.GONE);