Android AutoCompeleteTextView 没有给出正确的结果
Android AutoCompeleteTextView not gives proper result
我是 android 的新手,使用自定义 AutoCompleteTextView,这里是代码形式的 AutoCompleteText
<com.xxxxxxxx.supports.CustomAutoComplete
android:id="@+id/edit_search"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/transparent"
android:completionThreshold="3"
android:ellipsize="end"
android:fontFamily="@font/roboto"
android:gravity="center_vertical"
android:hint="@string/search_products_colors_more"
android:imeActionId="123456"
android:imeOptions="actionSearch"
android:inputType="textCapWords"
android:paddingLeft="10dp"
android:textColor="@color/dark_text_color"
android:textColorHint="@color/light_text_color"
android:textSize="@dimen/font_14sp" />
This is list comes when I search some thing over server
When I clicked on first item Steel Grey 显示如下。
我无法找出错误,有时会出现,有时不会。
请帮忙。
编辑更新:
public class CustomAutoComplete extends android.support.v7.widget.AppCompatAutoCompleteTextView {
private static final int MESSAGE_TEXT_CHANGED = 100;
private static final int DEFAULT_AUTOCOMPLETE_DELAY = 750;
private int mAutoCompleteDelay = DEFAULT_AUTOCOMPLETE_DELAY;
private ProgressBar mLoadingIndicator;
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
CustomAutoComplete.super.performFiltering((CharSequence) msg.obj, msg.arg1);
}
};
public CustomAutoComplete(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setLoadingIndicator(ProgressBar progressBar) {
mLoadingIndicator = progressBar;
}
public void setAutoCompleteDelay(int autoCompleteDelay) {
mAutoCompleteDelay = autoCompleteDelay;
}
@Override
protected void performFiltering(CharSequence text, int keyCode) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.VISIBLE);
}
mHandler.removeMessages(MESSAGE_TEXT_CHANGED);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), mAutoCompleteDelay);
}
@Override
public void onFilterComplete(int count) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.GONE);
}
super.onFilterComplete(count);
}
}
型号Class在下方
public class SearchResults {
private String suggetions, suggetionId;
public SearchResults(String suggetions, String suggetionId) {
this.suggetions = suggetions;
this.suggetionId = suggetionId;
}
public String getSuggetions() {
return suggetions;
}
public String getSuggetionId() {
return suggetionId;
}
public void setSuggetionId(String suggetionId) {
this.suggetionId = suggetionId;
}}
片段中的代码class
public CustomAutoComplete edit_search;
edit_search.setThreshold(3);
edit_search.setAdapter(new SearchAdapter(getActivity(), resultList, SearchItems.this)); // 'this' is Activity instance
edit_search.setLoadingIndicator(progress_search);
edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
try {
getPerspective().closeKeyboard();
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
if (resultList.size() != 0) {
if (edit_search.getText().length() > 2) {
String text = resultList.get(0).getSuggetions();
Log.e(TAG, "Text : " + text);
if (text.equalsIgnoreCase("No Results!")) {
edit_search.dismissDropDown();
layout_no_result.setVisibility(View.VISIBLE);
layout_mic.setVisibility(View.GONE);
} else {
layout_no_result.setVisibility(View.GONE);
layout_mic.setVisibility(View.VISIBLE);
getPerspective().openProdcuctList("0", text.trim());
}
} else if (edit_search.getText().length() < 3 && edit_search.getText().length() > 0) {
getPerspective().showMessage("Enter minimum three characters!");
} else if (edit_search.getText().length() <= 0) {
getPerspective().showMessage("Please enter your search query!");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
});
edit_search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (edit_search.getText().length() == 0) {
layout_no_result.setVisibility(View.GONE);
layout_mic.setVisibility(View.VISIBLE);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
现在适配器 class 代码是
public class SearchAdapter extends BaseAdapter implements Filterable {
public Context context;
private List<SearchResults> resultsList;
SearchItems searchItems;
Perspective perspective;
private LayoutInflater inflater;
public Perspective getPerspective() {
if (perspective == null)
perspective = (Perspective) context;
return perspective;
}
public SearchAdapter(Context context, List<SearchResults> resultsList, SearchItems searchItems) {
this.context = context;
this.resultsList = resultsList;
this.searchItems = searchItems;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return resultsList.size();
}
@Override
public Object getItem(int position) {
return resultsList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.custom_search_result_row, parent, false);
viewHolder.txt_item_name = (TextView) convertView.findViewById(R.id.txt_item_name);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_item_name.setText(resultsList.get(position).getSuggetions());
viewHolder.txt_item_name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String query = resultsList.get(position).getSuggetions();
Log.e("Search","Query : "+query);
// searchItems.edit_search.setText(query);
if (!query.equals("No Results!")) {
getPerspective().closeKeyboard();
searchItems.edit_search.dismissDropDown();
getPerspective().openProdcuctList("0", query);
}
}
});
return convertView;
}
class ViewHolder {
TextView txt_item_name;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
List<SearchResults> listSuggs = findSuggastions(context, constraint.toString());
filterResults.values = listSuggs;
filterResults.count = listSuggs.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
resultsList = (List<SearchResults>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
}
private List<SearchResults> findSuggastions(Context context, String title) {
resultsList.clear();
return resultsList = getSearchResults(title);
}
private List<SearchResults> getSearchResults(final String keyword) {
String tag_string_req = "req_top_search";
StringRequest strReq = new StringRequest(Request.Method.POST,
APIs.url_api_url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.e("SearchAdapter", "Response : " + response);
JSONArray object = new JSONArray(response);
//resultsList.clear();
for (int i = 0; i < object.length(); i++) {
JSONObject jsonObject = object.getJSONObject(i);
String prod_id = jsonObject.getString("product_id");
String prod_nam = jsonObject.getString("name");
SearchResults searchSuggs = new SearchResults(prod_nam, prod_id);
resultsList.add(searchSuggs);
}
if (resultsList.size() == 1) {
String prod_nam = resultsList.get(0).getSuggetions();
if (prod_nam.equalsIgnoreCase("No Results!")) {
searchItems.edit_search.dismissDropDown();
searchItems.layout_no_result.setVisibility(View.VISIBLE);
searchItems.layout_mic.setVisibility(View.GONE);
} else {
searchItems.layout_no_result.setVisibility(View.GONE);
searchItems.layout_mic.setVisibility(View.VISIBLE);
}
}else {
getPerspective().closeKeyboard();
}
notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("keyword", keyword);
return params;
}
};
strReq.setRetryPolicy(new RetryPolicy() {
@Override
public void retry(VolleyError arg0) throws VolleyError {
}
@Override
public int getCurrentTimeout() {
return 0;
}
@Override
public int getCurrentRetryCount() {
return 0;
}
});
strReq.setShouldCache(false);
Controller.getInstance().addToRequestQueue(strReq, tag_string_req);
return resultsList;
}
}
我更新了代码,
只需覆盖您要显示的 toString 方法和 return 数据。
public class SearchResults {
private String suggetions, suggetionId;
public SearchResults(String suggetions, String suggetionId) {
this.suggetions = suggetions;
this.suggetionId = suggetionId;
}
public String getSuggetions() {
return suggetions;
}
public String getSuggetionId() {
return suggetionId;
}
public void setSuggetionId(String suggetionId) {
this.suggetionId = suggetionId;
}
@Override
public final String toString()
{
return suggetions;
}
}
我是 android 的新手,使用自定义 AutoCompleteTextView,这里是代码形式的 AutoCompleteText
<com.xxxxxxxx.supports.CustomAutoComplete
android:id="@+id/edit_search"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/transparent"
android:completionThreshold="3"
android:ellipsize="end"
android:fontFamily="@font/roboto"
android:gravity="center_vertical"
android:hint="@string/search_products_colors_more"
android:imeActionId="123456"
android:imeOptions="actionSearch"
android:inputType="textCapWords"
android:paddingLeft="10dp"
android:textColor="@color/dark_text_color"
android:textColorHint="@color/light_text_color"
android:textSize="@dimen/font_14sp" />
This is list comes when I search some thing over server When I clicked on first item Steel Grey 显示如下。
我无法找出错误,有时会出现,有时不会。 请帮忙。
编辑更新:
public class CustomAutoComplete extends android.support.v7.widget.AppCompatAutoCompleteTextView {
private static final int MESSAGE_TEXT_CHANGED = 100;
private static final int DEFAULT_AUTOCOMPLETE_DELAY = 750;
private int mAutoCompleteDelay = DEFAULT_AUTOCOMPLETE_DELAY;
private ProgressBar mLoadingIndicator;
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
CustomAutoComplete.super.performFiltering((CharSequence) msg.obj, msg.arg1);
}
};
public CustomAutoComplete(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setLoadingIndicator(ProgressBar progressBar) {
mLoadingIndicator = progressBar;
}
public void setAutoCompleteDelay(int autoCompleteDelay) {
mAutoCompleteDelay = autoCompleteDelay;
}
@Override
protected void performFiltering(CharSequence text, int keyCode) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.VISIBLE);
}
mHandler.removeMessages(MESSAGE_TEXT_CHANGED);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), mAutoCompleteDelay);
}
@Override
public void onFilterComplete(int count) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.GONE);
}
super.onFilterComplete(count);
}
}
型号Class在下方
public class SearchResults {
private String suggetions, suggetionId;
public SearchResults(String suggetions, String suggetionId) {
this.suggetions = suggetions;
this.suggetionId = suggetionId;
}
public String getSuggetions() {
return suggetions;
}
public String getSuggetionId() {
return suggetionId;
}
public void setSuggetionId(String suggetionId) {
this.suggetionId = suggetionId;
}}
片段中的代码class
public CustomAutoComplete edit_search;
edit_search.setThreshold(3);
edit_search.setAdapter(new SearchAdapter(getActivity(), resultList, SearchItems.this)); // 'this' is Activity instance
edit_search.setLoadingIndicator(progress_search);
edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
try {
getPerspective().closeKeyboard();
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
if (resultList.size() != 0) {
if (edit_search.getText().length() > 2) {
String text = resultList.get(0).getSuggetions();
Log.e(TAG, "Text : " + text);
if (text.equalsIgnoreCase("No Results!")) {
edit_search.dismissDropDown();
layout_no_result.setVisibility(View.VISIBLE);
layout_mic.setVisibility(View.GONE);
} else {
layout_no_result.setVisibility(View.GONE);
layout_mic.setVisibility(View.VISIBLE);
getPerspective().openProdcuctList("0", text.trim());
}
} else if (edit_search.getText().length() < 3 && edit_search.getText().length() > 0) {
getPerspective().showMessage("Enter minimum three characters!");
} else if (edit_search.getText().length() <= 0) {
getPerspective().showMessage("Please enter your search query!");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
});
edit_search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (edit_search.getText().length() == 0) {
layout_no_result.setVisibility(View.GONE);
layout_mic.setVisibility(View.VISIBLE);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
现在适配器 class 代码是
public class SearchAdapter extends BaseAdapter implements Filterable {
public Context context;
private List<SearchResults> resultsList;
SearchItems searchItems;
Perspective perspective;
private LayoutInflater inflater;
public Perspective getPerspective() {
if (perspective == null)
perspective = (Perspective) context;
return perspective;
}
public SearchAdapter(Context context, List<SearchResults> resultsList, SearchItems searchItems) {
this.context = context;
this.resultsList = resultsList;
this.searchItems = searchItems;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return resultsList.size();
}
@Override
public Object getItem(int position) {
return resultsList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.custom_search_result_row, parent, false);
viewHolder.txt_item_name = (TextView) convertView.findViewById(R.id.txt_item_name);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_item_name.setText(resultsList.get(position).getSuggetions());
viewHolder.txt_item_name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String query = resultsList.get(position).getSuggetions();
Log.e("Search","Query : "+query);
// searchItems.edit_search.setText(query);
if (!query.equals("No Results!")) {
getPerspective().closeKeyboard();
searchItems.edit_search.dismissDropDown();
getPerspective().openProdcuctList("0", query);
}
}
});
return convertView;
}
class ViewHolder {
TextView txt_item_name;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
List<SearchResults> listSuggs = findSuggastions(context, constraint.toString());
filterResults.values = listSuggs;
filterResults.count = listSuggs.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
resultsList = (List<SearchResults>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
}
private List<SearchResults> findSuggastions(Context context, String title) {
resultsList.clear();
return resultsList = getSearchResults(title);
}
private List<SearchResults> getSearchResults(final String keyword) {
String tag_string_req = "req_top_search";
StringRequest strReq = new StringRequest(Request.Method.POST,
APIs.url_api_url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.e("SearchAdapter", "Response : " + response);
JSONArray object = new JSONArray(response);
//resultsList.clear();
for (int i = 0; i < object.length(); i++) {
JSONObject jsonObject = object.getJSONObject(i);
String prod_id = jsonObject.getString("product_id");
String prod_nam = jsonObject.getString("name");
SearchResults searchSuggs = new SearchResults(prod_nam, prod_id);
resultsList.add(searchSuggs);
}
if (resultsList.size() == 1) {
String prod_nam = resultsList.get(0).getSuggetions();
if (prod_nam.equalsIgnoreCase("No Results!")) {
searchItems.edit_search.dismissDropDown();
searchItems.layout_no_result.setVisibility(View.VISIBLE);
searchItems.layout_mic.setVisibility(View.GONE);
} else {
searchItems.layout_no_result.setVisibility(View.GONE);
searchItems.layout_mic.setVisibility(View.VISIBLE);
}
}else {
getPerspective().closeKeyboard();
}
notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("keyword", keyword);
return params;
}
};
strReq.setRetryPolicy(new RetryPolicy() {
@Override
public void retry(VolleyError arg0) throws VolleyError {
}
@Override
public int getCurrentTimeout() {
return 0;
}
@Override
public int getCurrentRetryCount() {
return 0;
}
});
strReq.setShouldCache(false);
Controller.getInstance().addToRequestQueue(strReq, tag_string_req);
return resultsList;
}
}
我更新了代码,
只需覆盖您要显示的 toString 方法和 return 数据。
public class SearchResults {
private String suggetions, suggetionId;
public SearchResults(String suggetions, String suggetionId) {
this.suggetions = suggetions;
this.suggetionId = suggetionId;
}
public String getSuggetions() {
return suggetions;
}
public String getSuggetionId() {
return suggetionId;
}
public void setSuggetionId(String suggetionId) {
this.suggetionId = suggetionId;
}
@Override
public final String toString()
{
return suggetions;
}
}