我正在尝试添加搜索框..
我知道搜索框代码如下所示。但是我很困惑如何添加和放置... .MainActvity类无法访问listview,因为它是在CountryXmlParser中创建的,而CountryXmlParser类不会扩展Actvity?I我发布了MainActvity和CountryXmlParser的代码
SearchBox代码
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
String searchString=searchBox.getText().toString();
int textLength=searchString.length();
//clear the initial data <span class="h9umc81m835" id="h9umc81m835_8">set</span>
list.clear();
for(int i=0;i<originalValues.size();i++)
{
String countryName=originalValues.get(i).get("country").toString();
if(textLength<=countryName.length()){
//compare the String in EditText with Names in the ArrayList
if(searchString.equalsIgnoreCase(countryName.substring(0,textLength)))
searchResults.add(originalValues.get(i));
}
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
MainActvity.java
Public class MainActivity extends Activity {
EditText searchBox;
ArrayList<HashMap<String, Object>> searchResults;
ArrayList<HashMap<String, Object>> originalValues;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchBox = (EditText)findViewById(R.id.searchBox);
/** This is the XML data to be parsed */
String xmlData = "<countries>" +
"<country name='India' flag='"+Integer.toString(R.drawable.india) +"'>" +
"<language>Hindi</language>" +
"<capital city='New Delhi' />" +
"<currency code='INR'>Indian Rupee</currency>" +
"</country>" +
"<country name='Pakistan' flag='"+Integer.toString(R.drawable.pakistan) +"'>" +
"<language>Urdu</language>" +
"<capital city='Islamabad' />" +
"<currency code='PKR'>Pakistani Rupee</currency>" +
"</country>" +
"<country name='Sri Lanka' flag='"+Integer.toString(R.drawable.srilanka) +"'>" +
"<language>Sinhala</language>" +
"<capital city='Sri Jayawardenapura Kotte' />" +
"<currency code='LKR'>Sri Lankan Rupee</currency>" +
"</country>" +
"<country name='China' flag='"+Integer.toString(R.drawable.china) +"'>" +
"<language>Chineese</language>" +
"<capital city='Beijing' />" +
"<currency code='CNY'>Renminbi</currency>" +
"</country>" +
"<country name='Bangladesh' flag='"+Integer.toString(R.drawable.bangladesh) +"'>" +
"<language>Bangla</language>" +
"<capital city='Dhaka' />" +
"<currency code='BDT'>Taka</currency>" +
"</country>" +
"<country name='Nepal' flag='"+Integer.toString(R.drawable.nepal) +"'>" +
"<language>Nepal Bhasa</language>" +
"<capital city='Kathmandu' />" +
"<currency code='NPR'>Nepalese rupee</currency>" +
"</country>" +
"<country name='Afghanistan' flag='"+Integer.toString(R.drawable.afghanistan) +"'>" +
"<language>Dari Persian</language>" +
"<capital city='Kabul' />" +
"<currency code='AFN'>Afghani</currency>" +
"</country>" +
"<country name='North Korea' flag='"+Integer.toString(R.drawable.nkorea) +"'>" +
"<language>Korean</language>" +
"<capital city='Pyongyang' />" +
"<currency code='KPW'>North Korean won</currency>" +
"</country>" +
"<country name='South Korea' flag='"+Integer.toString(R.drawable.skorea) +"'>" +
"<language>Korean</language>" +
"<capital city='Seoul' />" +
"<currency code='KRW'>South Korean won</currency>" +
"</country>" +
"<country name='Japan' flag='"+Integer.toString(R.drawable.japan) +"'>" +
"<language>Japanese</language>" +
"<capital city='Tokyo' />" +
"<currency code='JPY'>Yen</currency>" +
"</country>" +
"</countries>";
/** The parsing of the xml data is done in a non-ui thread */
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
/** Start parsing xml data */
listViewLoaderTask.execute(xmlData);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
/** Doing the parsing of xml data in a non-ui thread */
@Override
protected SimpleAdapter doInBackground(String... xmlData) {
StringReader reader = new StringReader(xmlData[0]);
CountryXmlParser countryXmlParser = new CountryXmlParser();
List<HashMap<String, String>> countries = null;
try{
/** Getting the parsed data as a List construct */
countries = countryXmlParser.parse(reader);
}catch(Exception e){
Log.d("Exception",e.toString());
}
/** Keys used in Hashmap */
String[] from = { "country","flag","details"};
/** Ids of views in listview_layout */
int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details};
/** Instantiating an adapter to store each items
* R.layout.listview_layout defines the layout of each item
*/
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
return adapter;
}
@Override
protected void onPostExecute(SimpleAdapter adapter) {
/** Getting a reference to listview of main.xml layout file */
ListView listView = ( ListView ) findViewById(R.id.lv_countries);
adapter = adapter;
originalValues=new ArrayList<HashMap<String,Object>>();
originalValues.add(hm);
searchResults=new ArrayList<HashMap<String,Object>>(originalValues);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
String searchString=searchBox.getText().toString();
int textLength=searchString.length();
//clear the initial data <span class="h9umc81m835" id="h9umc81m835_8">set</span>
searchResults.clear();
for(int i=0;i<originalValues.size();i++)
{
String countryName=originalValues.get(i).get("country").toString();
if(textLength<=countryName.length()){
//compare the String in EditText with Names in the ArrayList
if(searchString.equalsIgnoreCase(countryName.substring(0,textLength)))
searchResults.add(originalValues.get(i));
}
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
/** Setting the adapter containing the country list to listview */
listView.setAdapter(adapter);
}
}
}
CountryXmlParser.java
public class CountryXmlParser { {
private static final String ns = null;
/** This is the only function need to be called from outside the class */
public List<HashMap<String, String>> parse(Reader reader)
throws XmlPullParserException, IOException{
try{
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(reader);
parser.nextTag();
return readCountries(parser);
}finally{
}
}
/** This method read each country in the xml data and add it to List */
private List<HashMap<String, String>> readCountries(XmlPullParser parser)
throws XmlPullParserException,IOException{
List<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
parser.require(XmlPullParser.START_TAG, ns, "countries");
while(parser.next() != XmlPullParser.END_TAG){
if(parser.getEventType() != XmlPullParser.START_TAG){
continue;
}
String name = parser.getName();
if(name.equals("country")){
list.add(readCountry(parser));
}
else{
skip(parser);
}
}
return list;
}
/** This method read a country and returns its corresponding HashMap construct */
private HashMap<String, String> readCountry(XmlPullParser parser)
throws XmlPullParserException, IOException{
parser.require(XmlPullParser.START_TAG, ns, "country");
String countryName = parser.getAttributeValue(ns, "name");
String flag = parser.getAttributeValue(ns, "flag");
String language="";
String capital="";
String currencyCode="";
String currency="";
while(parser.next() != XmlPullParser.END_TAG){
if(parser.getEventType() != XmlPullParser.START_TAG){
continue;
}
String name = parser.getName();
if(name.equals("language")){
language = readLanguage(parser);
}else if(name.equals("capital")){
capital = parser.getAttributeValue(ns, "city");
readCapital(parser);
}else if(name.equals("currency")){
currencyCode = parser.getAttributeValue(ns, "code");
currency = readCurrency(parser);
}else{
skip(parser);
}
}
String details = "Language : " + language + "\n" +
"Capital : " + capital + "\n" +
"Currency : " + currency + "(" + currencyCode + ")";
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("country", countryName);
hm.put("flag", flag);
hm.put("details",details);
return hm;
}
/** Process language tag in the xml data */
private String readLanguage(XmlPullParser parser)
throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "language");
String language = readText(parser);
return language;
}
/** Process Capital tag in the xml data */
private void readCapital(XmlPullParser parser)
throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "capital");
parser.nextTag();
}
/** Process Currency tag in the xml data */
private String readCurrency(XmlPullParser parser)
throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "currency");
String currency = readText(parser);
return currency;
}
/** Getting Text from an element */
private String readText(XmlPullParser parser)
throws IOException, XmlPullParserException{
String result = "";
if(parser.next()==XmlPullParser.TEXT){
result = parser.getText();
parser.nextTag();
}
return result;
}
private void skip(XmlPullParser parser)
throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
答案 0 :(得分:0)
保留对适配器的引用并告诉它过滤结果:
adapter.getFilter().filter(sometext);
如果从getFilter()
返回的过滤器不适合您,您可以通过覆盖Filterable interface.
编辑: 尝试这样的事情: 在您的Activity中,在onCreate之前将ListView,Adapter和searchbox定义为类变量。在onCreate中,找到searchBox。
Public class MainActivity extends Activity {
ListView listView;
SimpleAdapter adapter;
EditText searchBox;
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(..);
searchBox = (EditText)findViewById(...);
...
在ListViewLoaderTask
onPostExecute
保存这些引用并添加侦听器:
listView = ( ListView ) findViewById(R.id.lv_countries);
adapter = adapter;
/** Setting the adapter containing the country list to listview */
listView.setAdapter(adapter);
//set textwatcher
searchBox.addTextChangeListener(...)
在前面提到的textwatcher afterTextChanged
过滤结果中