我现在正在努力解决这个问题。我正在用edittext构建一个可过滤的列表。该列表最初填充得很好,但是一旦我在编辑文本字段中输入了一些内容。整个列表都消失了,并且没有返回任何结果。以下是我的代码。
注意:我的代码主要基于 sacoskun 的帖子。
ThreedListViewActivity.java
public class ThreedListViewActivity extends ActionBarActivity
{
// All static variables
static final String URL = "http://api.androidhive.info/music/music.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
ListView list;
ThreedListAdapterFilterable adapter;
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
EditText filterText = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.threed_listview);
setTitle(R.string.view_3d);
list=(ListView)findViewById(R.id.list);
adapter = new ThreedListAdapterFilterable(this, songsList);
new MyAsyncTask().execute();
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString());
}
};
public class MyAsyncTask extends AsyncTask<Void,Void,Void>{
private final ProgressDialog dialog=new ProgressDialog(ThreedListViewActivity.this);
@Override
protected Void doInBackground(Void... params) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
return null;
}
@Override
protected void onPreExecute()
{
dialog.setMessage("Loading ...");
dialog.show();
dialog.setCancelable(false);
}
@Override
protected void onPostExecute(Void result)
{
if(dialog.isShowing() == true)
{
dialog.dismiss();
}
// Getting adapter by passing xml data ArrayList
list.setAdapter(adapter);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_items, menu);
return true;
}
}
ThreedListAdapterFilterable.java
public class ThreedListAdapterFilterable extends BaseAdapter implements Filterable {
private Activity activity;
ArrayList<HashMap<String, String>> mDataShown;
ArrayList<HashMap<String, String>> mAllData;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public ThreedListAdapterFilterable(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
mDataShown= (ArrayList<HashMap<String, String>>) d;
mAllData = (ArrayList<HashMap<String, String>>) mDataShown.clone();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return mDataShown.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.threed_listrow, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = mDataShown.get(position);
// Setting all values in listview
title.setText(song.get(ThreedListViewActivity.KEY_TITLE));
artist.setText(song.get(ThreedListViewActivity.KEY_ARTIST));
duration.setText(song.get(ThreedListViewActivity.KEY_DURATION));
imageLoader.DisplayImage(song.get(ThreedListViewActivity.KEY_THUMB_URL), thumb_image);
return vi;
}
public Filter getFilter() {
Filter nameFilter = new Filter() {
@SuppressWarnings("unchecked")
@Override
public String convertResultToString(Object resultValue) {
return ((HashMap<String, String>)(resultValue)).get(ThreedListViewActivity.KEY_TITLE);
}
@Override
protected FilterResults performFiltering(CharSequence s) {
if(s != null)
{
ArrayList<HashMap<String, String>> tmpAllData = mAllData;
ArrayList<HashMap<String, String>> tmpDataShown = mDataShown;
tmpDataShown.clear();
for(int i = 0; i < tmpAllData.size(); i++)
{
if(tmpAllData.get(i).get(ThreedListViewActivity.KEY_TITLE).toLowerCase().startsWith(s.toString().toLowerCase()))
{
tmpDataShown.add(tmpAllData.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = tmpDataShown;
filterResults.count = tmpDataShown.size();
return filterResults;
}
else
{
return new FilterResults();
}
}
@Override
protected void publishResults(CharSequence s,
FilterResults results) {
if(results != null && results.count > 0)
{
notifyDataSetChanged();
}
}};
return nameFilter;
}
}
编辑: 这是一个更新的适配器,将过滤我的列表。但是,当我退格输入文本中的文本时,它不会更新我的列表。
public class ProjectListAdapter extends BaseAdapter implements Filterable{
private Activity activity;
ArrayList<HashMap<String, String>> mDataShown;
ArrayList<HashMap<String, String>> mAllData;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
HashMap<String, String> song = new HashMap<String, String>();
ArrayList<HashMap<String, String>> filteredItems;
public ProjectListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
mDataShown= (ArrayList<HashMap<String, String>>) d;
mAllData = (ArrayList<HashMap<String, String>>) mDataShown.clone();
filteredItems = mDataShown;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mDataShown.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi;
if(convertView==null){
vi=new View(activity);
vi = inflater.inflate(R.layout.recents_listrow, null);
}else{
vi = (View)convertView;
}
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.company); // artist name
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
title.setText(filteredItems.get(position).get(RecentsFragment.KEY_TITLE));
artist.setText(filteredItems.get(position).get(RecentsFragment.KEY_COMPANY));
imageLoader.DisplayImage(filteredItems.get(position).get(RecentsFragment.KEY_THUMB_URL), thumb_image);
return vi;
}
public Filter getFilter() {
Filter nameFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null && constraint.toString().length() > 0) {
constraint = constraint.toString().toUpperCase();
ArrayList<HashMap<String, String>> filt = mDataShown;
ArrayList<HashMap<String, String>> tmpItems = mAllData;
filt.clear();
for(int i = 0; i < tmpItems.size(); i++) {
if(tmpItems.get(i).get(RecentsFragment.KEY_TITLE).toLowerCase().startsWith(constraint.toString().toLowerCase()))
{
filt.add(tmpItems.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.count = filt.size();
filterResults.values = filt;
return filterResults;
}else{
return new FilterResults();
}
}
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
mDataShown = (ArrayList<HashMap<String, String>>)results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return nameFilter;
}
}
我正在尝试实现的列表片段:RecentsFragment
public class RecentsFragment extends ListFragment {
// All static variables
static final String URL = "http://www.sundancepost.com/ivue/projects.xml";
// XML node keys
static final String KEY_PROJECT = "project"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_COMPANY = "company";
static final String KEY_THUMB_URL = "thumb_url";
int mCurCheckPosition = 0;
ListView list;
ProjectListAdapter adapter;
ArrayList<HashMap<String, String>> projectsList = new ArrayList<HashMap<String, String>>();
EditText filterText = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recents_list, container, false);
list = (ListView)view.findViewById(android.R.id.list);
filterText = (EditText)view.findViewById(R.id.filter_box);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(null == savedInstanceState){
ConnectivityManager cMgr = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (cMgr.getActiveNetworkInfo() != null && cMgr.getActiveNetworkInfo().isConnectedOrConnecting()) {
new MyAsyncTask().execute();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Please check your internet connection");
builder.setTitle("Failed to download resources");
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
adapter = new ProjectListAdapter(getActivity(), projectsList);
list.requestFocus();
list.setTextFilterEnabled(true);
filterText.addTextChangedListener(filterTextWatcher);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra("title",projectsList.get(position).get(KEY_TITLE));
intent.putExtra("company", projectsList.get(position).get(KEY_COMPANY));
startActivity(intent);
}
});
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt("workaround", mCurCheckPosition);
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
@Override
public void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public class MyAsyncTask extends AsyncTask<Void,Void,Void>{
private final ProgressDialog recents_dialog = new ProgressDialog(getActivity());
@Override
protected Void doInBackground(Void... params) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_PROJECT);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_COMPANY, parser.getValue(e, KEY_COMPANY));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
projectsList.add(map);
}
return null;
}
@Override
protected void onPreExecute()
{
projectsList.clear();
recents_dialog.setMessage("Loading ...");
recents_dialog.show();
recents_dialog.setCancelable(false);
}
@Override
protected void onPostExecute(Void result)
{
if(recents_dialog.isShowing() == true)
{
recents_dialog.dismiss();
}
// Getting adapter by passing xml data ArrayList
list.setAdapter(adapter);
}
}
}