我有一个列表视图,每行包含项目和子项目。我有一个EditText字段,我想用它来键入文本时筛选列表。我希望能够搜索项目和子项目。有人能指出我如何做到这一点的正确方向吗?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.google.android.gms.maps.model.Marker;
public class FarmMarketList extends RSFM
{
ListView marketList;
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> addresses = new ArrayList<String>();
ArrayAdapter<String> adapter;
EditText listSearch;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.farm_market_list);
marketList = (ListView) findViewById(R.id.listFarmMarkets);
listSearch = (EditText) findViewById(R.id.listSearch);
for(Marker m : list)
{
titles.add(m.getTitle());
addresses.add(m.getSnippet());
}
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for(int i = 0; i < titles.size(); i++)
{
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("title", titles.get(i));
datum.put("subtitle", addresses.get(i));
data.add(datum);
}
SimpleAdapter simpleAdapter = new SimpleAdapter(FarmMarketList.this, data, android.R.layout.simple_list_item_2, new String[] {"title", "subtitle"}, new int[] {android.R.id.text1, android.R.id.text2});
marketList.setAdapter(simpleAdapter);
// Row Selection
marketList.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
TextView text1 = (TextView) v.findViewById(android.R.id.text1);
TextView text2 = (TextView) v.findViewById(android.R.id.text2);
Intent i = new Intent(FarmMarketList.this, FarmMarketDetails.class);
i.putExtra("selectedTitle", text1.getText());
i.putExtra("selectedAddress", text2.getText());
startActivity(i);
}
});
}
}
编辑:我添加了此代码,但是当我开始在EditText字段中输入时,它会导致应用程序崩溃。
listSearch.addTextChangedListener(new TextWatcher()
{
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3)
{
FarmMarketList.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
}
});
答案 0 :(得分:1)
我通过添加
来实现它marketList.setTextFilterEnabled(true);
并将onTextChange()方法中的行更改为
FarmMarketList.this.simpleAdapter.getFilter().filter(cs);