在Fragment里面的ListView中实现搜索

时间:2014-11-13 21:50:14

标签: android listview android-fragments android-listview

嘿伙计们,我正在尝试在内置到片段中的listview中实现搜索功能 列表视图工作正常但是当我在edittext上键入以进行搜索时它会消失

我的代码:

public class DrinksFragment extends Fragment {

    private View rootView;
    private ArrayAdapter<DrinksList> adapter;
    private List<DrinksList> drinks;
    private ListView lv;
    ArrayList<DrinksList> mAllData;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_drinks_fragment, container, false);
        populateDrinksList();
        doSearch();
        return rootView;
    }

    private void doSearch() {
        final EditText et = (EditText)rootView.findViewById(R.id.searchListDrinks);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = et.getText().toString().toLowerCase(Locale.getDefault());
            adapter.filter(text);
            }
        });
    }



    private void populateDrinksList() {
        drinks = new ArrayList<DrinksList>();
        drinks.add(new DrinksList(R.drawable.coca, "Coca Cola", 2.50));
        drinks.add(new DrinksList(R.drawable.cocalight, "Coca Cola Light", 2.50));
        drinks.add(new DrinksList(R.drawable.cocazero, "Coca Cola Zero", 2.50));
        drinks.add(new DrinksList(R.drawable.orange, "Fanta Orange", 2.50));
        drinks.add(new DrinksList(R.drawable.lemon, "Fanta Lemon", 2.50));
        drinks.add(new DrinksList(R.drawable.ble, "Fanta Blue", 2.50));
        drinks.add(new DrinksList(R.drawable.sprite, "Sprite", 2.50));
        drinks.add(new DrinksList(R.drawable.soda, "Soda Water", 2.50));
        drinks.add(new DrinksList(R.drawable.tonic, "Tonic Water", 2.50));
        drinks.add(new DrinksList(R.drawable.ioli, "Sparkling Water Ioli", 2.50));
        drinks.add(new DrinksList(R.drawable.perrier, "Sparkling Water Perrier", 2.50));
        drinks.add(new DrinksList(R.drawable.nero, "Still Water", 2.00));
        drinks.add(new DrinksList(R.drawable.redbull, "Red Bull", 4.00));
        drinks.add(new DrinksList(R.drawable.zelita, "Zelita", 2.50));
        lv = (ListView)rootView.findViewById(R.id.drinksListView);
        adapter = new MyCustomDrinksListAdapter(getActivity().getApplicationContext(), R.layout.list_item, drinks);
        lv.setAdapter(adapter);
    }

}public class DrinksFragment extends Fragment {

    private View rootView;
    private ArrayAdapter<DrinksList> adapter;
    private List<DrinksList> drinks;
    private ListView lv;
    ArrayList<DrinksList> mAllData;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_drinks_fragment, container, false);
        populateDrinksList();
        doSearch();
        return rootView;
    }

    private void doSearch() {
        final EditText et = (EditText)rootView.findViewById(R.id.searchListDrinks);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                DrinksFragment.this.adapter.getFilter().filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }



    private void populateDrinksList() {
        drinks = new ArrayList<DrinksList>();
        drinks.add(new DrinksList(R.drawable.coca, "Coca Cola", 2.50));
        drinks.add(new DrinksList(R.drawable.cocalight, "Coca Cola Light", 2.50));
        drinks.add(new DrinksList(R.drawable.cocazero, "Coca Cola Zero", 2.50));
        drinks.add(new DrinksList(R.drawable.orange, "Fanta Orange", 2.50));
        drinks.add(new DrinksList(R.drawable.lemon, "Fanta Lemon", 2.50));
        drinks.add(new DrinksList(R.drawable.ble, "Fanta Blue", 2.50));
        drinks.add(new DrinksList(R.drawable.sprite, "Sprite", 2.50));
        drinks.add(new DrinksList(R.drawable.soda, "Soda Water", 2.50));
        drinks.add(new DrinksList(R.drawable.tonic, "Tonic Water", 2.50));
        drinks.add(new DrinksList(R.drawable.ioli, "Sparkling Water Ioli", 2.50));
        drinks.add(new DrinksList(R.drawable.perrier, "Sparkling Water Perrier", 2.50));
        drinks.add(new DrinksList(R.drawable.nero, "Still Water", 2.00));
        drinks.add(new DrinksList(R.drawable.redbull, "Red Bull", 4.00));
        drinks.add(new DrinksList(R.drawable.zelita, "Zelita", 2.50));
        lv = (ListView)rootView.findViewById(R.id.drinksListView);
        adapter = new MyCustomDrinksListAdapter(getActivity().getApplicationContext(), R.layout.list_item, drinks);
        lv.setAdapter(adapter);
    }

}

我的适配器:

public class MyCustomDrinksListAdapter extends ArrayAdapter<DrinksList> {


    private List<DrinksList> items = null;
    private ArrayList<DrinksList> arraylist;
    public MyCustomDrinksListAdapter(Context context, int layoutId, List<DrinksList> items) {
        super(context, layoutId, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View arrayView = convertView;
        if(arrayView == null){
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            arrayView = vi.inflate(R.layout.list_item, parent, false);
        }

        DrinksList currentPosition = getItem(position);
        if(currentPosition != null){
            ImageView image = (ImageView)arrayView.findViewById(R.id.product_image_coffee);
            image.setImageResource(currentPosition.getImage());

            TextView name = (TextView)arrayView.findViewById(R.id.product_name_coffee);
            name.setText(currentPosition.getName());

            TextView price = (TextView)arrayView.findViewById(R.id.product_price_coffee);
            price.setText(String.format("%.2f", currentPosition.getPrice()));
        }
        return arrayView;
    }

    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        items.clear();
        if (charText.length() == 0) {
            items.addAll(arraylist);
        } else {
            for (DrinksList wp : arraylist) {
                if (wp.getName().toLowerCase(Locale.getDefault())
                        .contains(charText)) {
                    items.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }
}

我试过跟随android开发者的例子,但我不能。 提前致谢!! 任何想法??

4 个答案:

答案 0 :(得分:7)

而不是在Adapter类中添加filter方法。 ..将它添加到你的片段..像这样......

    public class DrinksFragment extends Fragment {

    private View rootView;
    private ArrayAdapter<DrinksList> adapter;
    private List<DrinksList> drinks;
    private ListView lv;
    ArrayList<DrinksList> mAllData=new ArrayList<DrinksList>();
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_drinks_fragment, container, false);
        populateDrinksList();
        doSearch();
        return rootView;
    }

    private void doSearch() {
        final EditText et = (EditText)rootView.findViewById(R.id.searchListDrinks);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = et.getText().toString().toLowerCase(Locale.getDefault());
            filter(text);
            }
        });
    }



    private void populateDrinksList() {
        drinks = new ArrayList<DrinksList>();
        drinks.add(new DrinksList(R.drawable.coca, "Coca Cola", 2.50));
        drinks.add(new DrinksList(R.drawable.cocalight, "Coca Cola Light", 2.50));
        drinks.add(new DrinksList(R.drawable.cocazero, "Coca Cola Zero", 2.50));
        drinks.add(new DrinksList(R.drawable.orange, "Fanta Orange", 2.50));
        drinks.add(new DrinksList(R.drawable.lemon, "Fanta Lemon", 2.50));
        drinks.add(new DrinksList(R.drawable.ble, "Fanta Blue", 2.50));
        drinks.add(new DrinksList(R.drawable.sprite, "Sprite", 2.50));
        drinks.add(new DrinksList(R.drawable.soda, "Soda Water", 2.50));
        drinks.add(new DrinksList(R.drawable.tonic, "Tonic Water", 2.50));
        drinks.add(new DrinksList(R.drawable.ioli, "Sparkling Water Ioli", 2.50));
        drinks.add(new DrinksList(R.drawable.perrier, "Sparkling Water Perrier", 2.50));
        drinks.add(new DrinksList(R.drawable.nero, "Still Water", 2.00));
        drinks.add(new DrinksList(R.drawable.redbull, "Red Bull", 4.00));
        drinks.add(new DrinksList(R.drawable.zelita, "Zelita", 2.50));

mAllData.addAll(drinks);
        lv = (ListView)rootView.findViewById(R.id.drinksListView);
        adapter = new MyCustomDrinksListAdapter(getActivity().getApplicationContext(),        R.layout.list_item, drinks);
        lv.setAdapter(adapter);
    }


public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        drinks .clear();
        if (charText.length() == 0) {
            drinks.addAll(mAllData);
        } else {
            for (DrinksList wp : mAllData) {
                if (wp.getName().toLowerCase(Locale.getDefault())
                        .contains(charText)) {
                    drinks .add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }

}

你的Adapter类将保持原样(删除过滤器方法)..

 public class MyCustomDrinksListAdapter extends ArrayAdapter<DrinksList> {


   // private List<DrinksList> items = null; // no use
    private ArrayList<DrinksList> arraylist;
    public MyCustomDrinksListAdapter(Context context, int layoutId, List<DrinksList> items) {
        super(context, layoutId, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View arrayView = convertView;
        if(arrayView == null){
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            arrayView = vi.inflate(R.layout.list_item, parent, false);
        }

        DrinksList currentPosition = getItem(position);
        if(currentPosition != null){
            ImageView image = (ImageView)arrayView.findViewById(R.id.product_image_coffee);
            image.setImageResource(currentPosition.getImage());

            TextView name = (TextView)arrayView.findViewById(R.id.product_name_coffee);
            name.setText(currentPosition.getName());

            TextView price = (TextView)arrayView.findViewById(R.id.product_price_coffee);
            price.setText(String.format("%.2f", currentPosition.getPrice()));
        }
        return arrayView;
    }


}

谢谢。希望它有效...... !! 1

答案 1 :(得分:3)

您的自定义适配器必须实现Filterable接口,您应该覆盖getFilter()方法。

参考这个答案: How to implement getfilter() with custom adapter that extends baseadapter

答案 2 :(得分:2)

我发现问题出在MyCustomDrinksListAdapter类的构造函数上。 在构造函数中初始化arraylist,如下所示:

arraylist = new ArrayList<DrinksList>();
this.arraylist.addAll(items);

您不需要从基础适配器扩展只需更改构造函数。 它看起来你的另一件事是不熟悉ViewHolder的概念。在getView()中搜索并使用它可以提高效果。但你的剩余代码是正确的,但构造函数。 如果你需要任何其他帮助,你可以问。

答案 3 :(得分:1)

这是您需要用于在列表视图上实现临时的代码:

inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.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                          
    }
});

取自following教程。希望它有所帮助:)