我创建了一个列表视图,其中数据来自存储在string.xml
中的字符串数组。
我有一个edittext,我想从listview中搜索特定数据。我的listview数据包含这样的011德里德里...我怎么能这样做?
这是我的代码..
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arrayList);
Resources res = getResources();
String[] a = res.getStringArray(R.array.states);
arrayList.add("" + a);
adapter.notifyDataSetChanged();
editText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
答案 0 :(得分:3)
我希望以下代码适合您。
public class MainActivity extends Activity {
private ListView lv;
private EditText et;
String listview_array[]={"123","TWO","Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "1234", "iPhone 4S", "Samsung Galaxy Note 800", "Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
private ArrayList<String> array_sort = new ArrayList<String>();
int textlength = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.ListView01);
et = (EditText) findViewById(R.id.EditText01);
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listview_array));
int x= lv.getHeaderViewsCount ();
et.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
// Abstract Method of TextWatcher Interface.
}
public void beforeTextChanged(CharSequence s,
int start, int count, int after)
{
// Abstract Method of TextWatcher Interface.
}
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
textlength = et.getText().length();
array_sort.clear();
for (int i = 0; i < listview_array.length; i++)
{
if (textlength <= listview_array[i].length())
{
if (et.getText().toString().equalsIgnoreCase(
(String)
listview_array[i].subSequence(0,
textlength)))
{
array_sort.add(listview_array[i]);
}
}
}
lv.setAdapter(new ArrayAdapter<String>
(MainActivity.this,
android.R.layout.simple_list_item_1, array_sort));
}
});
}
}
答案 1 :(得分:1)
您可以这样搜索:
String text_to_search = editText.getText().toString();
for(String str : your_list) {
if(str.equals(text_to_search) {
//Do your operation
}
}
如果你想要一个索引,那么你可以使用我们传统的for
循环。
答案 2 :(得分:1)
在适配器中使用此代码。
public void filter(String charText) {
charText = charText.toLowerCase();
picList.clear();
if (charText.length() == 0) {
picList.addAll(listpicOrigin);
} else {
for (Picture pic : listpicOrigin) {
if (pic.getPicName().toLowerCase().contains(charText)) {
picList.add(pic);
}
}
}
notifyDataSetChanged();
}
您可以参考this tutorial
了解更多细节