bug天天有,今年特别多~!
好好的SearchView,别人用的好好的,GOOGLE的APIDEMO里面也好好的,就是我的不行~!
真的是我运气背吗,我想是的!天将降大任于斯人也必先苦其心志,劳其。。。
1.最先SearchView我是使用的菜单的方式添加~!但是添加后点击图标居然它毫无反应,不展开,默认不是应该出现编辑框么?
android:actionViewClass="android.support.v7.widget.SearchView"依然如此~!
2.然后我就说暂时不管这个了,先来获取这个SearchView然后来动态设置试试,没想到获取不了,报错了,说是空的对象引用!
但是我打印了一下它是否为空,居然是不为空,但是如果你调用了它的方法,比如toString都会报错,我还看了看下面的关联错误,说是
FragmentActivity的298行错误,我一看FragmentActivity是v4包的,估计就是这个错~!
相信很多人都开始用AndroidStudio了,我用Eclipse没有这个问题!但我用的Eclipse编写的就可以啊,也是这个v4包,大神求解啊~!
对比AndroidStudio的FragmentActivity和Eclispe里面FragmentActivity里面确实不一样了,一个900多行,一个600多行。但是我不可能去改
系统级别的东东吧!
3.最后的解决办法只有去除菜单xml中的actionViewClass属性,动态的在Activity的onCreateOptionsMenu里面添加了这个SearchView了!
遇到这个问题的同学很少,百度了下没几个,希望大神指明这个错误的原因,提出更好的解决办法!
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_cook, menu);
setSearchView(menu);
return super.onCreateOptionsMenu(menu);
}
/**
* 设置查询菜单项
* @param menu
*/
private void setSearchView(Menu menu) {
//1.找到menuItem并动态设置SearchView
MenuItem item = menu.getItem(0);
searchView = new SearchView(this);
item.setActionView(searchView);
//2.设置搜索的背景为白色
item.collapseActionView();
searchView.setQuery("", false);
searchView.setBackgroundResource(R.drawable.searchview_select);
//3.设置为默认展开状态,图标在外面
searchView.setIconifiedByDefault(false);
searchView.setQueryHint("菜谱名");
//4.设置搜索的监听事件
searchView.setOnQueryTextListener(this);
//显示并启用提交按钮
searchView.setSubmitButtonEnabled(true);
//获取搜索编辑组件
searchSrcText = (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text);
//5.图片点击事件
View searchButton = searchView.findViewById(R.id.submit_area);
searchButton.setVisibility(View.GONE);
searchView.getRootView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!searchStr.isEmpty()) {
getCookData(searchStr);
}
}
});
}
当然我们用SearchView肯定是用来搜索和保存一些搜索的记录的,在搜索成功后肯定需要加入相关的字符集到Adapter中,然后给SearchView设置Adapter。SearchVIew是用的SimpleCursorAdapter,系统也是帮我们写好了的。我们通过searchView.setSuggestionAdapter(adapter);就设置了其会显示的搜索历史了!全部代码:
package com.cq.cake.cook;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.cq.cake.adapter.CookAdapter;
import com.cq.cake.data.Constant;
import com.cq.cake.entity.CookEntity;
import com.cq.cake.http.DBOpenHelperUtils;
import com.cq.cake.http.VolleyHttp;
import com.cq.cake.util.CakeShowDialog;
import com.cq.cake.util.L;
import com.cq.cake.weather.R;
import com.cq.cake.weather.WeatherActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
public class CookActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private RecyclerView cookRecyclerView;
private String searchStr = "";
private SearchView searchView;
private SearchView.SearchAutoComplete searchSrcText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cook_layout);
initView();
getCookData(DBOpenHelperUtils.selectLastCookName(this));
}
private void initView() {
cookRecyclerView = (RecyclerView) findViewById(R.id.cook_recyclerview);
cookRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private ProgressBar createProgressBar(Activity activity, Drawable customIndeterminateDrawable) {
// activity根部的ViewGroup,其实是一个FrameLayout
FrameLayout rootContainer = (FrameLayout) activity.findViewById(android.R.id.content);
// 给progressbar准备一个FrameLayout的LayoutParams
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// 设置对齐方式为:屏幕居中对其
lp.gravity = Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL;
ProgressBar progressBar = new ProgressBar(activity);
progressBar.setVisibility(View.GONE);
progressBar.setLayoutParams(lp);
// 自定义小菊花
if (customIndeterminateDrawable != null) {
progressBar.setIndeterminateDrawable(customIndeterminateDrawable);
}
// 将菊花添加到FrameLayout中
rootContainer.addView(progressBar);
return progressBar;
}
/**
* 1.查询菜谱数据
*/
private void getCookData(String menu) {
if (TextUtils.isEmpty(menu))
return;
// T.showShort(CookActivity.this, "查询的菜谱名:" + menu);
if (searchView!=null&&searchView.isFocusable()){
searchView.clearFocus();
}
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
HashMap map = new HashMap();
map.put("key", Constant.JUHE_COOK_KEY);
map.put("menu", menu);
VolleyHttp.doPostJSONObject(this, Constant.JUHE_COOK_QUERY, map, new Response.Listener() {
@Override
public void onResponse(JSONObject jsonObject) {
try {
int resultcode = jsonObject.getInt("resultcode");
if (resultcode == 200) {
JSONObject result = jsonObject.getJSONObject("result");
JSONArray data = result.getJSONArray("data");
setCookData(data);
DBOpenHelperUtils.save(CookActivity.this, searchStr);
} else {
String reason = jsonObject.getString("reason");
new CakeShowDialog(CookActivity.this, reason).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
new CakeShowDialog(CookActivity.this, "数据异常").show();
}
}
);
}
/**
* 2.设置菜谱介绍
*
* @param data
* @throws JSONException
*/
private void setCookData(JSONArray data) throws JSONException, IOException {
List list = JSON.parseArray(data.toString(), CookEntity.class);
cookRecyclerView.setAdapter(new CookAdapter(this, list, R.layout.item_cook));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_cook, menu);
setSearchView(menu);
return super.onCreateOptionsMenu(menu);
}
/**
* 设置查询菜单项
* @param menu
*/
private void setSearchView(Menu menu) {
//1.找到menuItem并动态设置SearchView
MenuItem item = menu.getItem(0);
searchView = new SearchView(this);
item.setActionView(searchView);
//2.设置搜索的背景为白色
item.collapseActionView();
searchView.setQuery("", false);
searchView.setBackgroundResource(R.drawable.searchview_select);
//3.设置为默认展开状态,图标在外面
searchView.setIconifiedByDefault(false);
searchView.setQueryHint("菜谱名");
//4.设置搜索的监听事件
searchView.setOnQueryTextListener(this);
//显示并启用提交按钮
searchView.setSubmitButtonEnabled(true);
//获取搜索编辑组件
searchSrcText = (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text);
//5.图片点击事件
View searchButton = searchView.findViewById(R.id.submit_area);
searchButton.setVisibility(View.GONE);
searchView.getRootView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!searchStr.isEmpty()) {
getCookData(searchStr);
}
}
});
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_cook_search:
loadSuggest();
break;
case R.id.menu_flush:
getCookData(DBOpenHelperUtils.selectLastCookName(this));
case R.id.menu_clear_suggest:
clearSuggest();
break;
case R.id.menu_weather:
startActivity(new Intent(CookActivity.this, WeatherActivity.class));
break;
case R.id.menu_video_cached:
startActivity(new Intent(CookActivity.this,CachedActivity.class));
break;
case R.id.menu_video_caching:
startActivity(new Intent(CookActivity.this,CachingActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
/**
* 清除搜索历史
*/
private void clearSuggest() {
DBOpenHelperUtils.deleteTable(this);
}
/**
* 加载建议
*/
private void loadSuggest() {
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.mytextview, DBOpenHelperUtils.selectAll(this), new String[]{"cook_name"},
new int[]{R.id.textview});
searchView.setSuggestionsAdapter(adapter);
// searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
// @Override
// public void onFocusChange(View v, boolean hasFocus) {
// if (hasFocus) {
// L.e("编辑框被点击了!");
//
//
// }
//
// }
// });
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int position) {
return true;
}
@Override
public boolean onSuggestionClick(int position) {
Cursor c = (Cursor) adapter.getItem(position);
String selectCookName = c.getString(c.getColumnIndex(c.getColumnName(1)));
L.e("c.getString(1):" + selectCookName);
searchSrcText.setText(selectCookName);
getCookData(selectCookName);
return true;
}
});
}
@Override
public boolean onQueryTextSubmit(String query) {
searchStr = query;
getCookData(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
searchStr = newText.isEmpty() ? "" : newText;
return true;
}
}