我在我的简单Android应用程序的listview中添加搜索功能时遇到问题。我被关注了这篇文章[https://workspaces.codeproject.com/vatsag/customized-android-listview-with-image-and-text][1],但我无法确定如何添加搜索功能。
这是xparser.java
:
public class XParser extends DefaultHandler {
ArrayList<String> idlist = new ArrayList<String>();
ArrayList<String> namalist = new ArrayList<String>();
ArrayList<String> menulist = new ArrayList<String>();
ArrayList<String> alamatlist = new ArrayList<String>();
ArrayList<String> iconlist = new ArrayList<String>();
//temp variable to store the data chunk read while parsing
private String tempStore = null;
public XParser() {
// TODO Auto-generated constructor stub
}
/*
* Clears the tempStore variable on every start of the element
* notification
*
* */
public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equalsIgnoreCase("id")) {
tempStore = "";
} else if (localName.equalsIgnoreCase("nama")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("menu")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("alamat")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("icon")) {
tempStore = "";
}
else {
tempStore = "";
}
}
/*
* updates the value of the tempStore variable into
* corresponding list on receiving end of the element
* notification
* */
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if (localName.equalsIgnoreCase("id")) {
idlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("nama")) {
namalist.add(tempStore);
}
else if (localName.equalsIgnoreCase("menu")) {
menulist.add(tempStore);
}
else if (localName.equalsIgnoreCase("alamat")) {
alamatlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("icon")) {
iconlist.add(tempStore);
}
tempStore = "";
}
/*
* adds the incoming data chunk of character data to the
* temp data variable - tempStore
*
* */
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
tempStore += new String(ch, start, length);
}
}
这是BinderData.java
public class BinderData extends BaseAdapter {
// XML node keys
static final String KEY_TAG = "rmdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAMA = "nama";
static final String KEY_MENU = "menu";
static final String KEY_ALAMAT = "alamat";
static final String KEY_ICON = "icon";
LayoutInflater inflater;
ImageView thumb_image;
List<HashMap<String,String>> rmDataCollection;
ViewHolder holder;
public BinderData() {
// TODO Auto-generated constructor stub
}
public BinderData(Activity act, List<HashMap<String,String>> map) {
this.rmDataCollection = map;
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
return idlist.size();
return rmDataCollection.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null){
vi = inflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.tvNama = (TextView)vi.findViewById(R.id.tvNama); // city name
holder.tvMenu = (TextView)vi.findViewById(R.id.tvMenu); // city weather overview
holder.tvRMImage =(ImageView)vi.findViewById(R.id.list_image); // thumb image
vi.setTag(holder);
}
else{
holder = (ViewHolder)vi.getTag();
}
// Setting all values in listview
holder.tvNama.setText(rmDataCollection.get(position).get(KEY_NAMA));
holder.tvMenu.setText(rmDataCollection.get(position).get(KEY_MENU));
//Setting an image
String uri = "drawable/"+ rmDataCollection.get(position).get(KEY_ICON);
int imageResource = vi.getContext().getApplicationContext().getResources().getIdentifier(uri, null, vi.getContext().getApplicationContext().getPackageName());
Drawable image = vi.getContext().getResources().getDrawable(imageResource);
holder.tvRMImage.setImageDrawable(image);
return vi;
}
/*
*
* */
static class ViewHolder{
TextView tvNama;
TextView tvMenu;
ImageView tvRMImage;
}
}
这是WeatherActiviy.java
:
public class WeatherActivity extends Activity implements OnQueryTextListener {
// XML node keys
static final String KEY_TAG = "rmdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAMA = "nama";
static final String KEY_MENU = "menu";
static final String KEY_ALAMAT = "alamat";
static final String KEY_ICON = "icon";
// List items
ListView list;
EditText inputSearch;
BinderData adapter = null;
List<HashMap<String,String>> rmDataCollection;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (getAssets().open("weatherdata.xml"));
rmDataCollection = new ArrayList<HashMap<String,String>>();
// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList weatherList = doc.getElementsByTagName("rmdata");
HashMap<String,String> map = null;
for (int i = 0; i < weatherList.getLength(); i++) {
map = new HashMap<String,String>();
Node firstWeatherNode = weatherList.item(i);
if(firstWeatherNode.getNodeType() == Node.ELEMENT_NODE){
Element firstWeatherElement = (Element)firstWeatherNode;
//-------
NodeList idList = firstWeatherElement.getElementsByTagName(KEY_ID);
Element firstIdElement = (Element)idList.item(0);
NodeList textIdList = firstIdElement.getChildNodes();
//--id
map.put(KEY_ID, ((Node)textIdList.item(0)).getNodeValue().trim());
//2.-------
NodeList cityList = firstWeatherElement.getElementsByTagName(KEY_NAMA);
Element firstCityElement = (Element)cityList.item(0);
NodeList textCityList = firstCityElement.getChildNodes();
//--city
map.put(KEY_NAMA, ((Node)textCityList.item(0)).getNodeValue().trim());
//3.-------
NodeList tempList = firstWeatherElement.getElementsByTagName(KEY_MENU);
Element firstTempElement = (Element)tempList.item(0);
NodeList textTempList = firstTempElement.getChildNodes();
//--city
map.put(KEY_MENU, ((Node)textTempList.item(0)).getNodeValue().trim());
/*
//4.-------
NodeList condList = firstWeatherElement.getElementsByTagName(KEY_ALAMAT);
Element firstCondElement = (Element)condList.item(0);
NodeList textCondList = firstCondElement.getChildNodes();
//--city
map.put(KEY_ALAMAT, ((Node)textCondList.item(0)).getNodeValue().trim());
//5.-------
NodeList speedList = firstWeatherElement.getElementsByTagName(KEY_SPEED);
Element firstSpeedElement = (Element)speedList.item(0);
NodeList textSpeedList = firstSpeedElement.getChildNodes();
//--city
map.put(KEY_SPEED, ((Node)textSpeedList.item(0)).getNodeValue().trim());
*/
//6.-------
NodeList iconList = firstWeatherElement.getElementsByTagName(KEY_ICON);
Element firstIconElement = (Element)iconList.item(0);
NodeList textIconList = firstIconElement.getChildNodes();
//--city
map.put(KEY_ICON, ((Node)textIconList.item(0)).getNodeValue().trim());
//Add to the Arraylist
rmDataCollection.add(map);
}
}
BinderData bindingData = new BinderData(this,rmDataCollection);
list = (ListView) findViewById(R.id.list);
Log.i("BEFORE", "<<------------- Before SetAdapter-------------->>");
list.setAdapter(bindingData);
Log.i("AFTER", "<<------------- After SetAdapter-------------->>");
list.setTextFilterEnabled(true);
// search
inputSearch = (EditText) findViewById (R.id.inputSearch);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
((Filterable) WeatherActivity.this.rmDataCollection).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
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
}
});
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(WeatherActivity.this, SampleActivity.class);
// parameters
i.putExtra("position", String.valueOf(position + 1));
/* selected item parameters
* 1. City name
* 2. Weather
* 3. Wind speed
* 4. Temperature
* 5. Weather icon
*/
i.putExtra("city", rmDataCollection.get(position).get(KEY_NAMA));
i.putExtra("weather", rmDataCollection.get(position).get(KEY_MENU));
i.putExtra("windspeed", rmDataCollection.get(position).get(KEY_ALAMAT));
i.putExtra("icon", rmDataCollection.get(position).get(KEY_ICON));
// start the sample activity
startActivity(i);
}
});
}
catch (IOException ex) {
Log.e("Error", ex.getMessage());
}
catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
if (TextUtils.isEmpty(newText))
{
list.clearTextFilter();
}
else
{
list.setFilterText(newText.toString());
}
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
}