前言
項(xiàng)目需要艾少,要求自定義一個(gè)searchview卡乾,其實(shí)Android自帶的就有這個(gè)控件,而且做得很好缚够,還有一些是通過修改樣式來(lái)打造说订,筆者更喜歡把它抽出來(lái)成為一個(gè)控件,這樣在以后的使用中會(huì)方便很多潮瓶,于是在網(wǎng)上找了找資料陶冷,綜合各大神的代碼,給出自己的解決方案毯辅。有不準(zhǔn)確的地方埂伦,歡迎各位指出,筆者加以改正思恐,共同學(xué)習(xí)沾谜。
上效果圖:
1、這個(gè)搜索框控件的布局并不是很復(fù)雜胀莹,左上方那個(gè)搜索的小圖片是個(gè)ImageView基跑,中間是EditText,最右邊的小垃圾桶是個(gè)ImageView描焰,只是在未輸入搜索內(nèi)容的時(shí)候visibility為gone媳否,而搜索框下方是個(gè)gridview,gridview放的是搜索的熱詞荆秦,顯示搜索內(nèi)容的是一個(gè)webview篱竭,gridview是蓋在webview上面的,之前有小伙伴問我怎么蓋在另外一個(gè)控件上步绸,原理很簡(jiǎn)單掺逼,把gridview的xml布局代碼寫在webview的xml布局代碼下方就行。瓤介。吕喘。(很簡(jiǎn)單但是很有效)
2赘那、這種由幾個(gè)控件組成的自定義控件首先要做的是寫布局文件,布局文件沒什么好說(shuō)的氯质,上代碼:
<?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"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:id="@+id/search_area"
android:background="@drawable/rect_gray"
android:layout_height="wrap_content">
<ImageView
android:layout_marginLeft="10dp"
android:src="@android:drawable/ic_menu_search"
android:id="@+id/search_iv_search"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/search_et_input"
android:layout_gravity="center_vertical"
android:layout_margin="10dp"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textSize="16sp"
android:background="@null"
android:imeOptions="actionSearch"
android:inputType="text"
android:textCursorDrawable="@null"
android:hint="Google search"/>
<ImageView
android:visibility="gone"
android:layout_marginRight="10dp"
android:src="@android:drawable/ic_menu_delete"
android:id="@+id/search_iv_delete"
android:layout_gravity="right|center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/search_area"
android:id="@+id/search_wv_result"
/>
<GridView
android:layout_below="@id/search_area"
android:background="@drawable/rect_gray"
android:numColumns="2"
android:id="@+id/search_lv_tips"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</GridView >
</RelativeLayout>
3漓概、布局代碼中就可以猜測(cè)到,我們將在一個(gè)LinearLayout或者一個(gè)RelativeLayout中去操作病梢,我們讓這個(gè)自定義控件繼承自LinearLayout(當(dāng)然也可以繼承自RelativeLayout),這里可能需要頻繁的調(diào)用開始搜索的代碼梁肿,去做搜索onSearch()方法里的內(nèi)容蜓陌,還有就是每次搜索的時(shí)候都要隱藏鍵盤,
至于這個(gè)EditChangedListener吩蔑,只是為了在在輸入過程中動(dòng)態(tài)的一些操作 钮热,筆者也是第一次使用TextWatcher。有g(shù)ridview的地方就免不了adapter烛芬,通過外部設(shè)置給自定義控件一個(gè)adapter
直接上代碼吧:
public class YankeeSearchView extends LinearLayout implements View.OnClickListener {
private EditText etInput;
private ImageView ivDelete;
private ImageView ivSearch;
private Context mContext;
private GridView lvTips;
private WebView wvSearch;
private ArrayAdapter<String> mHintAdapter;
private SearchViewListener mListener;
public YankeeSearchView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
LayoutInflater.from(context).inflate(R.layout.search_layout, this);
initViews();
}
private void initViews() {
etInput = (EditText) findViewById(R.id.search_et_input);
ivDelete = (ImageView) findViewById(R.id.search_iv_delete);
ivSearch=(ImageView) findViewById(R.id.search_iv_search);
lvTips = (GridView) findViewById(R.id.search_lv_tips);
wvSearch= (WebView) findViewById(R.id.search_wv_result);
wvSearch.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
lvTips.setVisibility(GONE);
return false;
}
});
lvTips.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String text = lvTips.getAdapter().getItem(i).toString();
etInput.setText(text);
etInput.setSelection(text.length());
lvTips.setVisibility(View.GONE);
notifyStartSearching(text);
}
});
ivDelete.setOnClickListener(this);
ivSearch.setOnClickListener(this);
etInput.addTextChangedListener(new EditChangedListener());
etInput.setOnClickListener(this);
etInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
lvTips.setVisibility(GONE);
notifyStartSearching(etInput.getText().toString());
}
return true;
}
});
}
private void notifyStartSearching(String text){
if (mListener != null) {
mListener.onSearch(etInput.getText().toString());
}
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
public void setTipsHintAdapter(ArrayAdapter<String> adapter) {
this.mHintAdapter = adapter;
if (lvTips.getAdapter() == null) {
lvTips.setAdapter(mHintAdapter);
}
}
private class EditChangedListener implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (!"".equals(charSequence.toString())) {
ivDelete.setVisibility(VISIBLE);
lvTips.setVisibility(VISIBLE);
} else {
ivDelete.setVisibility(GONE);
if (mHintAdapter != null) {
lvTips.setAdapter(mHintAdapter);
}
lvTips.setVisibility(GONE);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.search_et_input:
lvTips.setVisibility(VISIBLE);
break;
case R.id.search_iv_delete:
etInput.setText("");
ivDelete.setVisibility(GONE);
break;
case R.id.search_iv_search:
lvTips.setVisibility(GONE);
notifyStartSearching(etInput.getText().toString());
break;
}
}
public void setSearchViewListener(SearchViewListener listener) {
mListener = listener;
}
public interface SearchViewListener {
void onSearch(String text);
}
public void setWebViewUrl(String url){
if (url!=null){
wvSearch.loadUrl(url);
wvSearch.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
}
}
4隧期、代碼里都是一些隱藏顯示的操作,比較重要的是對(duì)外的接口赘娄,還有就是setWebViewUrl()方法仆潮,用來(lái)對(duì)輸入內(nèi)容展開搜索。構(gòu)造函數(shù)里傳入了三個(gè)參數(shù)遣臼,傳入一個(gè)布局文件性置,如果要自定義item,可以寫一個(gè)adapter揍堰,demo中為了簡(jiǎn)單鹏浅,使用的是Android自帶的只有一個(gè)textview的布局,而adapter使用的是ArrayAdapter<String>屏歹,再有就是通過簡(jiǎn)單修改代碼就可以把gridview替換成ListView隐砸,筆者不操作了
5、至于調(diào)用蝙眶,在activity_main布局文件中只要添加:
<com.yankee.yankeesearchview.YankeeSearchView
android:id="@+id/main_search_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
6季希、在activity中,通過給searchview設(shè)置listener復(fù)寫onSearch()方法幽纷,在方法里操作胖眷,別忘了通過setTipsHintAdapter()方法設(shè)置adapter:
public class MainActivity extends AppCompatActivity{
private YankeeSearchView searchView;
private ArrayAdapter<String> hintAdapter;
private List<String> hintData;
private static int HINT_SIZE=6;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
}
private void initView() {
searchView = (YankeeSearchView) findViewById(R.id.main_search_layout);
searchView.setSearchViewListener(new YankeeSearchView.SearchViewListener() {
@Override
public void onSearch(String text) {
Toast.makeText(MainActivity.this, "Search Complete", Toast.LENGTH_SHORT).show();
searchView.setWebViewUrl("https://www.baidu.com/baidu?ie=utf-8&wd="+text);
}
});
searchView.setTipsHintAdapter(hintAdapter);
}
private void initData() {
hintData = new ArrayList<>(HINT_SIZE);
for (int i = 1; i <= HINT_SIZE; i++) {
hintData.add("Rio Olympic Games");
}
hintAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, hintData);
}
}