searchviewandroid
㈠ android searchview的問題
java">(StringnewText){
//dosomething...
//在這里根據newText對listView的數據進行過濾,然後更新
}
㈡ android searchview 怎麼改變默認的搜索圖標
Framework中SearchView的屬性如下:
<attr name="searchIcon" format="reference" />對應搜索圖標
在SearchView中直接指定即可
<SearchView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:searchIcon="@drawable/custom_search_icon"/>
㈢ 如何使用 SearchView 工具欄中Android
眾所周知,在使用ActionBar的時候,一堆的問題:這個文字能不能定製,位置能不能改變,圖標的間距怎麼控制神馬的,由此暴露出了ActionBar設計的不靈活。為此官方提供了ToolBar,並且提供了supprot library用於向下兼容。Toolbar之所以靈活,是因為它其實就是一個ViewGroup,我們在使用的時候和普通的組件一樣,在布局文件中聲明。
Part1:ToolBar的引入step1:設置style主題,主要任務是去除原本的ActionBar
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar"><!--Light.DarkActionBar表示默認的黑色主體的Actionbar-->
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/sky_blue</item>
<item name="colorPrimaryDark">@color/deep_blue</item>
<item name="colorAccent">@color/material_deep_teal_200</item>
<item name="android:textColorPrimary">@color/white</item>
</style>
colorPrimary表示標題欄ActionBar的顏色;colorPrimaryDark表示狀態欄的顏色; colorAccent表示輸入框,按鈕等被選中時的顏色; textColorPrimary表示標題欄(ActionBar或者ToolBar)中字體的顏色
當然啦,第一步的實現也可以在程序代碼中或者style里靜態或者動態地去掉ActionBar
step2:在你需要引入ToolBar的布局文件中引入ToolBar:
<android.support.v7.widget.Toolbar
android:id="@+id/main_toolbar"
android:theme="@style/ThemeOverlay.AppCompat.Dark"//這里的主題可以用來反襯toolBar的overFlow顏色
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/sky_blue"
></android.support.v7.widget.Toolbar>
因為colorPrimary是給ActionBar設定顏色的,因此如果我們使用ToolBar,就需要自己去設定ToolBar的背景顏色
setp3:在代碼中獲取ToolBar控制項以及實例化:
Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
toolbar.setNavigationIcon(R.mipmap.ic_toc_white_24dp);//設置ToolBar頭部圖標
toolbar.setTitle("ToolBar");//設置標題,也可以在xml中靜態實現
setSupportActionBar(toolbar);//使活動支持ToolBar
Part2:ToolBar里各SearchView的引入:
setp1:在menu/xxxx.xml的菜單布局文件將SearchView以菜單條目的方式加入到ToolBar中
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"
android:inputType="textCapWords"
android:imeOptions="actionSearch"
android:title="search" />
這中添加條目的方式和添加普通控制項的方式是一樣的,這里需要對showAsAction具體說明以下:
ifRoom表示當toolBar空間足夠時,顯示圖標在標題欄中,否則將它隱藏到ToolBar末端的overFlow中,點開overFlow只顯示item的title
CollapseActionView表示當前空間點開之後占據整個ToolBar空間
always表示總是顯示在標題欄中,當我們長按該item後,就會以Toast的方式顯示出它的title
never表示總是隱藏在overFlow中
step2:在Java程序代碼中實例SearchView
覆寫onCreateOptionsMenu方法,為什麼要在這個方法里實現對SearchView的實例化呢?因為toolBar里的點擊事件都以菜單的形式實現的,如果我們需要讓它隱藏到overFlow中,並且點擊菜單鍵並喚出,那麼就只需要把它的顯示方式設置為never即可。
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);//在菜單中找到對應控制項的item
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
Log.d("Tag", "menu create");
MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() {//設置打開關閉動作監聽
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
Toast.makeText(MainActivity.this, "onExpand", Toast.LENGTH_LONG).show();
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
Toast.makeText(MainActivity.this, "Collapse", Toast.LENGTH_LONG).show();
return true;
}
});
return super.onCreateOptionsMenu(menu);
㈣ 如何使用 SearchView 工具欄中Android
SearchView是android系統中內置的一個搜索框組件,可以很方便在添加在用戶界面之上,SearchView的使用:
1.創建布局 main.xml:
<LinearLayout 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:orientation="vertical" >
<SearchView
android:id="@+id/sv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:imeOptions="actionGo" />
</LinearLayout>
2.在顯示suggestion的時候會用到下面的布局文件:mytextview.xml
<?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="50sp"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingLeft="5sp"
android:textSize="18sp" />
</LinearLayout>
3.java中的使用代碼:main.java:
package xxx.xxx.xxx;
import java.lang.reflect.Field;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class Main extends Activity {
SearchView sv = null;
ListView lv = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sv = (SearchView) this.findViewById(R.id.sv);
sv.setIconifiedByDefault(false);
sv.setSubmitButtonEnabled(true);
sv.setQueryHint("查詢");
//通過反射,修改默認的樣式,可以從android的search_view.xml中找到需要的組件
try {
Field field = sv.getClass().getDeclaredField("mSubmitButton");
field.setAccessible(true);
ImageView iv = (ImageView) field.get(sv);
iv.setImageDrawable(this.getResources().getDrawable(
R.drawable.pointer));
} catch (Exception e) {
e.printStackTrace();
}
Cursor cursor = this.getTestCursor();
@SuppressWarnings("deprecation")
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.mytextview, cursor, new String[] { "tb_name" },
new int[] { R.id.textview });
sv.setSuggestionsAdapter(adapter);
sv.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String str) {
return false;
}
@Override
public boolean onQueryTextSubmit(String str) {
Toast.makeText(Main.this, str, Toast.LENGTH_SHORT).show();
return false;
}
});
}
//添加suggestion需要的數據
public Cursor getTestCursor() {
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(
this.getFilesDir() + "/my.db3", null);
Cursor cursor = null;
try {
String insertSql = "insert into tb_test values (null,?,?)";
db.execSQL(insertSql, new Object[] { "aa", 1 });
db.execSQL(insertSql, new Object[] { "ab", 2 });
db.execSQL(insertSql, new Object[] { "ac", 3 });
db.execSQL(insertSql, new Object[] { "ad", 4 });
db.execSQL(insertSql, new Object[] { "ae", 5 });
String querySql = "select * from tb_test";
cursor = db.rawQuery(querySql, null);
} catch (Exception e) {
String sql = "create table tb_test (_id integer primary key autoincrement,tb_name varchar(20),tb_age integer)";
db.execSQL(sql);
String insertSql = "insert into tb_test values (null,?,?)";
db.execSQL(insertSql, new Object[] { "aa", 1 });
db.execSQL(insertSql, new Object[] { "ab", 2 });
db.execSQL(insertSql, new Object[] { "ac", 3 });
db.execSQL(insertSql, new Object[] { "ad", 4 });
db.execSQL(insertSql, new Object[] { "ae", 5 });
String querySql = "select * from tb_test";
cursor = db.rawQuery(querySql, null);
}
return cursor;
}
}
㈤ android SearchView 輸入後按返回鍵無法返回
android searchView輸入後按返回鍵無法返回可能的原因如下:
當android 的代碼中,沒有對返回鍵進行監聽,用戶點擊返回鍵是不會有事件響應的。
android searchView該控制項存在bug,輸入之後,停留在該界面,無法跳轉。
㈥ android SearchView設置默認值
setQuery("2",false);
㈦ android SearchView 輸入後按返回鍵無法返回
android
searchView輸入後按返回鍵無法返回可能的原因如下:
1.
當android
的代碼中,沒有對返回鍵進行監聽,用戶點擊返回鍵是不會有事件響應的。
2.
android
searchView該控制項存在bug,輸入之後,停留在該界面,無法跳轉。
㈧ android怎麼使用SearchView啊
SearchView即時搜索提示功能,主要實現如下:
layout布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SearchView
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:iconifiedByDefault="true"
android:inputType="textCapWords"
android:imeOptions="actionSearch"
android:queryHint="" />
</RelativeLayout>
xml中主要配置有四個屬性,如下:
android:iconifiedByDefault表示搜索圖標是否在輸入框內。true效果更加
android:imeOptions設置IME options,即輸入法的回車鍵的功能,可以是搜索、下一個、發送、完成等等。這里actionSearch表示搜索
android:inputType輸入框文本類型,可控制輸入法鍵盤樣式,如numberPassword即為數字密碼樣式
android:queryHint輸入框默認文本
SearchView的幾個主要函數
setOnCloseListener(SearchView.OnCloseListener listener)表示點擊取消按鈕listener,默認點擊搜索輸入框
setOnQueryTextListener(SearchView.OnQueryTextListener listener)表示輸入框文字listener,包括public boolean onQueryTextSubmit(String query)開始搜索listener,public boolean onQueryTextChange(String newText)輸入框內容變化listener,兩個函數
java部分實現:
package cn.trinea.android.demo;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheledExecutorService;
import java.util.concurrent.ScheledFuture;
import java.util.concurrent.TimeUnit;
import android.app.ActionBar;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.SearchView;
import android.widget.SearchView.OnCloseListener;
import android.widget.Toast;
public class SearchViewDemo extends Activity {
private SearchView searchView;
private Context context;
private MyHandler handler;
// schele executor
private ScheledExecutorService scheledExecutor = Executors.newScheledThreadPool(10);
private String currentSearchTip;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_view_demo);
context = getApplicationContext();
handler = new MyHandler();
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_HOME_AS_UP
| ActionBar.DISPLAY_SHOW_CUSTOM);
setTitle(" ");
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View customActionBarView = inflater.inflate(R.layout.search_view_demo_title, null);
searchView = (SearchView)customActionBarView.findViewById(R.id.search_view);
searchView.setIconified(false);
searchView.setOnCloseListener(new OnCloseListener() {
@Override
public boolean onClose() {
// to avoid click x button and the edittext hidden
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextSubmit(String query) {
Toast.makeText(context, "begin search", Toast.LENGTH_SHORT).show();
return true;
}
public boolean onQueryTextChange(String newText) {
if (newText != null && newText.length() > 0) {
currentSearchTip = newText;
showSearchTip(newText);
}
return true;
}
});
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL
| Gravity.RIGHT);
actionBar.setCustomView(customActionBarView, params);
// show keyboard
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
public void showSearchTip(String newText) {
// excute after 500ms, and when excute, judge current search tip and newText
schele(new SearchTipThread(newText), 500);
}
class SearchTipThread implements Runnable {
String newText;
public SearchTipThread(String newText){
this.newText = newText;
}
public void run() {
// keep only one thread to load current search tip, u can get data from network here
if (newText != null && newText.equals(currentSearchTip)) {
handler.sendMessage(handler.obtainMessage(1, newText + " search tip"));
}
}
}
public ScheledFuture<?> schele(Runnable command, long delayTimeMills) {
return scheledExecutor.schele(command, delayTimeMills, TimeUnit.MILLISECONDS);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
onBackPressed();
return true;
}
}
return false;
}
private class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Toast.makeText(context, (String)msg.obj, Toast.LENGTH_SHORT).show();
break;
}
}
}
}
上面代碼在onQueryTextChange函數即輸入框內容每次變化時將一個數據獲取線程SearchTipThread放到ScheledExecutorService中,500ms後執行,在線程執行時判斷當前輸入框內容和要搜索內容,若相等則繼續執行,否則直接返回,避免不必要的數據獲取和多個搜索提示同時出現。
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
表示默認輸入法彈出
編輯框內容為空點擊取消的x按鈕,編輯框收縮,可在onClose中返回true
Java
1
2
3
4
5
6
7
searchView.setOnCloseListener(new OnCloseListener() {
@Override
public boolean onClose() {
return true;
}
});
searchView.onActionViewExpanded();表示在內容為空時不顯示取消的x按鈕,內容不為空時顯示.
searchView.setSubmitButtonEnabled(true);編輯框後顯示search按鈕,個人建議用android:imeOptions=」actionSearch」代替。
隱藏輸入法鍵盤
InputMethodManager inputMethodManager;
inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
private void hideSoftInput() {
if (inputMethodManager != null) {
View v = SearchActivity.this.getCurrentFocus();
if (v == null) {
return;
}
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
searchView.clearFocus();
}
}
其中SearchActivity為Activity的類名
㈨ android searchview 怎麼改變默認的搜索圖標
您好,很高興能幫助您,
在res/drawable-hdpi或res/drawable-ldpi或res/drawable-mdpi目錄下,加下你要顯示的圖片,最好後綴是為.png的,然後修改AndroidManifest.xml文件,裡面有這樣一行代碼<application android:icon="@drawable/icon" android:label="@string/app_name">,把它改為<application android:icon="@drawable/***" android:label="@string/app_name">(「***」表示你放入的圖片的名,比如你放入app.png,那麼就是android:icon="@drawable/app")
你的採納是我前進的動力,還有不懂的地方,請你繼續「追問」!
如你還有別的問題,可另外向我求助;答題不易,互相理解,互相幫助!