你好我是android studio的新手。我想在不使用数据库的情况下在操作栏上搜索ListView
项。目前,我的代码仅向ListView
显示多行文字。你能帮助我使用搜索小部件而不是editText来实现这一目标吗?
答案 0 :(得分:4)
<强> 1。添加搜索菜单
使用搜索菜单项创建菜单资源文件(单击搜索菜单项时,搜索小部件将显示在操作栏中)。
以下是我创建的示例菜单资源(res / menu / search_menu.xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/search"
android:title="Search"
android:icon="@drawable/search"
android:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="android.widget.SearchView" />
</menu>
在上面的菜单项中,collapseActionView属性允许您的SearchView展开以占用整个操作栏,并在不使用时折叠回正常的操作栏项
<强> 2。创建SearchableConfiguration
可搜索配置定义了SearchView的行为方式 需要在xml中定义它(res / xml / searchable.xml)。以下是可搜索的配置文件示例
<?xml version="1.0" encoding="utf-8"?>
<searchable
xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="Search friend">
</searchable>
然后将此元素添加到带有标记
的相关活动中<activity
android:name=".ui.FriendListActivity"
android:screenOrientation="portrait"
android:configChanges="orientation"
android:theme="@style/Theme.Yello"
android:windowSoftInputMode="stateHidden"
android:launchMode="singleTask"
android:parentActivityName=".ui.SensorDetailsActivity">
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable">
</meta-data>
</activity>
在我的场景中,我将把SearchView添加到FriendListActivity
第3。将菜单和SearchableConfiguration添加到活动
将可搜索配置与活动类
中的SearchView相关联@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);
SearchManager searchManager = (SearchManager)
getSystemService(Context.SEARCH_SERVICE);
searchMenuItem = menu.findItem(R.id.search);
searchView = (SearchView) searchMenuItem.getActionView();
searchView.setSearchableInfo(searchManager.
getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
return true;
}
现在SearchView已添加到活动中。但仍然搜索功能不起作用
<强> 4。添加搜索功能
在活动中实施SearchView.OnQueryTextListener
,现在需要覆盖两个新方法
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
此界面侦听SearchView中的文本更改事件
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
friendListAdapter.getFilter().filter(newText);
return true;
}
在这里onQueryTextChange函数用列表适配器做过滤,为了做过滤,适配器需要实现Filterable接口
4.Filterable adapter
在我的场景中,我使用BaseAdapter实现了Filterable接口
以下是我的适配器类(FriendListAdapter)
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.score.senzors.R;
import com.score.senzors.pojos.User;
import java.util.ArrayList;
/**
* Display friend list
*
*/
public class FriendListAdapter extends BaseAdapter implements Filterable {
private FriendListActivity activity;
private FriendFilter friendFilter;
private Typeface typeface;
private ArrayList<User> friendList;
private ArrayList<User> filteredList;
/**
* Initialize context variables
* @param activity friend list activity
* @param friendList friend list
*/
public FriendListAdapter(FriendListActivity activity, ArrayList<User> friendList) {
this.activity = activity;
this.friendList = friendList;
this.filteredList = friendList;
typeface = Typeface.createFromAsset(activity.getAssets(), "fonts/vegur_2.otf");
getFilter();
}
/**
* Get size of user list
* @return userList size
*/
@Override
public int getCount() {
return filteredList.size();
}
/**
* Get specific item from user list
* @param i item index
* @return list item
*/
@Override
public Object getItem(int i) {
return filteredList.get(i);
}
/**
* Get user list item id
* @param i item index
* @return current item id
*/
@Override
public long getItemId(int i) {
return i;
}
/**
* Create list row view
* @param position index
* @param view current list item view
* @param parent parent
* @return view
*/
@Override
public View getView(int position, View view, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary calls
// to findViewById() on each row.
final ViewHolder holder;
final User user = (User) getItem(position);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.friend_list_row_layout, parent, false);
holder = new ViewHolder();
holder.iconText = (TextView) view.findViewById(R.id.icon_text);
holder.name = (TextView) view.findViewById(R.id.friend_list_row_layout_name);
holder.iconText.setTypeface(typeface, Typeface.BOLD);
holder.iconText.setTextColor(activity.getResources().getColor(R.color.white));
holder.name.setTypeface(typeface, Typeface.NORMAL);
view.setTag(holder);
} else {
// get view holder back
holder = (ViewHolder) view.getTag();
}
// bind text with view holder content view for efficient use
holder.iconText.setText("#");
holder.name.setText(user.getEmail());
view.setBackgroundResource(R.drawable.friend_list_selector);
return view;
}
/**
* Get custom filter
* @return filter
*/
@Override
public Filter getFilter() {
if (friendFilter == null) {
friendFilter = new FriendFilter();
}
return friendFilter;
}
/**
* Keep reference to children view to avoid unnecessary calls
*/
static class ViewHolder {
TextView iconText;
TextView name;
}
/**
* Custom filter for friend list
* Filter content in friend list according to the search text
*/
private class FriendFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint!=null && constraint.length()>0) {
ArrayList<User> tempList = new ArrayList<User>();
// search content in friend list
for (User user : friendList) {
if (user.getEmail().toLowerCase().contains(constraint.toString().toLowerCase())) {
tempList.add(user);
}
}
filterResults.count = tempList.size();
filterResults.values = tempList;
} else {
filterResults.count = friendList.size();
filterResults.values = friendList;
}
return filterResults;
}
/**
* Notify about filtered list to ui
* @param constraint text
* @param results filtered result
*/
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredList = (ArrayList<User>) results.values;
notifyDataSetChanged();
}
}
}
在这里我定义了自定义Filter类FriendFilter进行过滤,我根据在SearchView中输入的名称过滤列表
答案 1 :(得分:0)
您可以使用AutoTextView
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.your_autotext_view);
textView.setAdapter(adapter);
private static final String[] COUNTRIES = new String[] {
"Belgium", "France", "Italy", "Germany", "Spain"};
如果您不理解此代码,请参阅此AutoTextView Example
答案 2 :(得分:0)
<EditText android:id="@+id/inputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search products.."
android:inputType="textVisiblePassword"/>
inputSearch =(EditText)findViewById(R.id.inputSearch);
启用搜索过滤器
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
如果您有任何疑问,可以参考此LINK