SearchView过滤ListView

时间:2012-12-11 13:31:40

标签: android android-listview searchview

我已经发布了一个过滤我的列表视图项的搜索视图。当我输入任何文本时,它会过滤列表,但是当我退出搜索视图时,它不会返回原始列表项。

public class PlacesListAdapter extends ArrayAdapter<Place> implements
        Filterable {
    public Context context;
    private List<Place> places, orig, itemDetailsrrayList;
    private PlaceFilter filter;

    public PlacesListAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    public PlacesListAdapter(Context context, int resource, List<Place> places) {
        super(context, resource, places);
        this.context = context;
        this.places = places;

        itemDetailsrrayList = places;
        orig = itemDetailsrrayList;

        filter = new PlaceFilter();
        // imageLoader = new ImageLoader(context.getApplicationContext());

    }

    public int getCount() {
        return itemDetailsrrayList.size();
    }

    public Place getItem(int position) {
        return itemDetailsrrayList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        // View view = convertView;
        // Place p = places.get(position);

        if (convertView == null) {
            LayoutInflater viewInflater;
            viewInflater = LayoutInflater.from(getContext());
            convertView = viewInflater.inflate(R.layout.item_place, null);

            holder = new ViewHolder();
            holder.placeTitle = (TextView) convertView
                    .findViewById(R.id.place_title);
            holder.placeDistance = (TextView) convertView
                    .findViewById(R.id.place_distance);
            holder.placeCategoryIcon = (ImageView) convertView
                    .findViewById(R.id.place_category_icon);

            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.placeTitle.setText(itemDetailsrrayList.get(position)
                .getPlaceTitle());
        holder.placeDistance.setText("200");
        holder.placeCategoryIcon.setImageResource(R.drawable.icon_category);

        return convertView;
    }

    static class ViewHolder {
        TextView placeId;
        TextView placeTitle;
        TextView placeDistance;
        ImageView placeCategoryIcon;
    }

    @Override
    public Filter getFilter() {
        // TODO Auto-generated method stub
        return filter;
    }

    private class PlaceFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults oReturn = new FilterResults();
            ArrayList<Place> results = new ArrayList<Place>();
            if (orig == null)
                orig = itemDetailsrrayList;
            if (constraint != null) {
                if (orig != null && orig.size() > 0) {
                    for (Place g : orig) {
                        if (g.getPlaceTitle().toLowerCase()
                                .contains(constraint.toString().toLowerCase()))
                            results.add(g);
                    }
                }
                oReturn.values = results;
            }
            return oReturn;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            itemDetailsrrayList = (ArrayList<Place>) results.values;
            notifyDataSetChanged();
        }

    }
}

MainActivity.java

public class MainActivity extends SherlockFragmentActivity implements
        SearchView.OnQueryTextListener {
    protected static CharSequence[] _categories = { "Amusement Park",
            "Bird Sanctuary", "Wild Life", "River", "Hill Station", "Temple",
            "Rafting", "Fishing", "Hiking", "Museums" };

    protected static boolean[] _selections = new boolean[_categories.length];

    private final String[] places = new String[] { "Mysore", "Bangalore",
            "Mangalore", "Wayanad", "Bandipur National Park", "Chickmaglur",
            "Bandipura", "Coorg", "Kodaikanal", "Hampi", "Ghati Subramanya",
            "Mekedatu", "Muththathhi", "Shivasamudram", "Talakadu",
            "Savana Durga" };

    public SearchView mSearchView;
    private TextView mStatusView;

    private Menu mainMenu = null;

    PlacesListAdapter adapter;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        setContentView(R.layout.activity_main);

        Log.i("Nomad", "onCreate");

        List<Place> thePlaces = new ArrayList<Place>();
        for (int i = 0; i < places.length; i++) {
            Place pl = new Place("NO_ID", places[i], "NO_DISTANCE",
                    "NO_CATEGORYICON");
            thePlaces.add(pl);
        }

        listView = (ListView) findViewById(R.id.place_list);
        adapter = new PlacesListAdapter(MainActivity.this, R.layout.item_place,
                thePlaces);

        listView.setAdapter(adapter);
        listView.setTextFilterEnabled(true);

        mSearchView = (SearchView) findViewById(R.id.action_search);

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> a, View view, int position,
                    long id) {

                Toast.makeText(MainActivity.this, "Test", Toast.LENGTH_SHORT);
                startActivity(new Intent(MainActivity.this, PlaceActivity.class));
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.i("Nomad", "onCreateOptionsMenu");
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.activity_main, menu);

        mainMenu = menu;

        MenuItem searchItem = menu.findItem(R.id.action_search);

        // Search View
        mSearchView = (SearchView) searchItem.getActionView();
        setupSearchView(searchItem);

        mSearchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // hide action item
                if (mainMenu != null) {
                    mainMenu.findItem(R.id.action_category).setVisible(false);
                    mainMenu.findItem(R.id.action_sort).setVisible(false);
                }

            }
        });
        mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                // re-show the action button
                if (mainMenu != null) {
                    mainMenu.findItem(R.id.action_category).setVisible(true);
                    mainMenu.findItem(R.id.action_sort).setVisible(true);
                }
                return false;

            }
        });

        Log.i("Nomad", "after setupSearchView()");
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

        case R.id.action_search:
            Toast.makeText(this, "Searh", Toast.LENGTH_LONG).show();
            Log.i("Nomad", "Click Search");
            break;

        case R.id.action_category:
            showDialog();
            break;
        case R.id.action_sort_alpha_az:
            Toast.makeText(this, "Alpha AZ", Toast.LENGTH_LONG).show();
            break;
        case R.id.action_sort_alpha_za:
            Toast.makeText(this, "Alpha ZA", Toast.LENGTH_LONG).show();
            break;
        case R.id.action_sort_dist_nf:
            Toast.makeText(this, "Dist NF", Toast.LENGTH_LONG).show();
            break;
        case R.id.action_sort_dist_fn:
            Toast.makeText(this, "Dist FN", Toast.LENGTH_LONG).show();
            break;
        default:
            // return super.onOptionsItemSelected(item);
            break;
        }
        return true;
    }

    private void setupSearchView(MenuItem searchItem) {
        mSearchView.setIconifiedByDefault(true);
        mSearchView.setOnQueryTextListener(this);
        mSearchView.setSubmitButtonEnabled(false);

        searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        // | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
    }

    public boolean onQueryTextChange(String newText) {
        Log.i("Nomad", "onQueryTextChange");

        if (TextUtils.isEmpty(newText)) {
            Log.i("Nomad", "onQueryTextChange Empty String");
            listView.clearTextFilter();
        } else {
            Log.i("Nomad", "onQueryTextChange " + newText.toString());
            adapter.getFilter().filter(newText.toString());
        }
        return true;
    }

    public boolean onQueryTextSubmit(String query) {
        Log.i("Nomad", "onQueryTextSubmit");
        return false;
    }

    public boolean onClose() {
        Log.i("Nomad", "onClose");
        return false;
    }

    protected boolean isAlwaysExpanded() {
        return false;
    }


}

1 个答案:

答案 0 :(得分:3)

由于这行,你的两个带有适配器对象的ArrayList指向同一个对象:

itemDetailsrrayList = places;
orig = itemDetailsrrayList;

orig列表应保持不变,以便您在需要时返回原始数据:

orig = new ArrayList<String>(itemDetailsrrayList);

如果这不能解决问题,您可能需要显示一些与搜索视图相关的代码。