【问题标题】:Search Functionality to ListView using BaseAdapter not populating List on search使用 BaseAdapter 对 ListView 的搜索功能不会在搜索时填充 List
【发布时间】:2015-11-04 15:33:49
【问题描述】:

我一直在尝试对 listView 进行简单的搜索,我可以使用 Volley 填充该列表视图,但到目前为止都无济于事。感谢 @Dhaval Patel 的帮助。但我现在遇到的问题是,当我搜索时,ListView 拒绝更改内容,从而使 who 在程序中的搜索无用

下面是我的代码:

public class MainActivity extends Activity {

   private ListView mList;
   private List<Movie> movieList = new ArrayList<Movie>();
   EditText inputSearch;


    protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
           setContentView(R.layout.activity_main);

       mList = (ListView) findViewById(R.id.list);
       inputSearch = (EditText) findViewById(R.id.inputSearch);


           adapter = new CustomListAdapter(this, movieList);
           mList.setAdapter(adapter);


        //SEARCH TEXTCHANGE
        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.toString());
                //FLAGS Cannot resolve method 'getFilter()' here
                }

             @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
             }
          });




    }



}

这也是我的 CustomListAdapter 类中的代码

public class CustomListAdapter extends BaseAdapter {

     private Activity activity;
     private LayoutInflater inflater;
     private List<Movie> movieItems;
     private String[] bgColors;
     private List<String>originalData = null;
     private List<String>filteredData = null;
     private ItemFilter mFilter = new ItemFilter();
        ImageLoader imageLoader = MyApplication.getInstance().getImageLoader();


         public CustomListAdapter(Activity activity, List<Movie> movieItems) {
             this.activity = activity;
             this.movieItems = movieItems;
             bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
         }
         @Override
         public int getCount() {
                return movieItems.size();
         }

         @Override
        public Object getItem(int location) {
             return movieItems.get(location);
         }

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

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

            if (inflater == null)
              inflater = (LayoutInflater) activity
                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             if (convertView == null)
                convertView = inflater.inflate(R.layout.list_row_image, null);

             if (imageLoader == null)
              imageLoader = MyApplication.getInstance().getImageLoader();
            NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);

             TextView serial = (TextView) convertView.findViewById(R.id.serial);
            TextView title = (TextView) convertView.findViewById(R.id.title);
            TextView rating = (TextView) convertView.findViewById(R.id.rating);
            TextView genre = (TextView) convertView.findViewById(R.id.genre);
            TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

            // getting movie data for the row
            Movie m = movieItems.get(position);

            // thumbnail image
            thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

            // title
            title.setText(m.getTitle());

            // rating
             rating.setText("Rating: " + String.valueOf(m.getRating()));

            // genre
            String genreStr = "";
            for (String str : m.getGenre()) {
              genreStr += str + ", ";
              }
            genreStr = genreStr.length() > 0 ? genreStr.substring(0,
                 genreStr.length() - 2) : genreStr;
             genre.setText(genreStr);

            // release year
             year.setText(String.valueOf(m.getYear()));

             String color = bgColors[position % bgColors.length];
            serial.setBackgroundColor(Color.parseColor(color));




            return convertView;
     }



     public Filter getFilter() {
         return mFilter;
     }

private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();

        FilterResults results = new FilterResults();

        final List<String> list = originalData;

        int count = list.size();
        final ArrayList<String> nlist = new ArrayList<String>(count);

        String filterableString ;

        for (int i = 0; i < count; i++) {
            filterableString = list.get(i);
            if (filterableString.toLowerCase().contains(filterString)) {
                nlist.add(filterableString);
            }
        }

        results.values = nlist;
        results.count = nlist.size();

        return results;
    }

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

}



}

所以有人可以告诉我我做错了什么。 提前致谢

【问题讨论】:

  • 如果您没有使用 Filter 类,我确信我可以轻松解决您的问题,请等待我发现使用 Filter 比自己操作更容易。
  • 我能够解决这个问题,但注意到我在此处发布的另一个问题 stackoverflow.com/questions/33529720/…

标签: android listview search android-listview


【解决方案1】:
private class ItemFilter extends Filter { 
   @Override 
   protected FilterResults performFiltering(CharSequence constraint) {

    String filterString = constraint.toString().toLowerCase();

    FilterResults results = new FilterResults();

    final List<Movie> list = movieItems;

    int count = list.size();
    final ArrayList<Movie> nlist = new ArrayList<Movie>(count);

    String filterableString ;

    for (int i = 0; i < count; i++) {
        filterableString = list.get(i).getName();
        if (filterableString.toLowerCase().contains(filterString)) {
            nlist.add(list.get(i));
        } 
    } 

    results.values = nlist;
    results.count = nlist.size();

    return results;
} 

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

} 

【讨论】:

  • 嗨@jily - 我用 ** filterableString = list.get(i).getTitle(); 替换了 filterableString = list.get(i).getName(); ** 但是 nlist.add(filterableString); 上的程序标志 ERROR:: 'add(com.npi.blureffect.model.Movie)' in 'java.util.ArrayList' 不能应用于'(java.lang.String)'
  • 嗨@OkechukwuEze ...将电影对象添加到nlist ...我已经编辑了代码..检查出来。
  • 我不敢相信我终于解决了这个搜索难题。感谢您和@sonic 但我意识到,在搜索后用正确的列表内容填充列表当我清除 EditView 搜索数据时,列表不会重新填充以前的内容,而是只保留搜索结果..您知道在清除 EditView 数据后如何恢复 ListView 及其以前的内容吗?
  • 我能够解决这个问题,但注意到我在此处发布的另一个问题 stackoverflow.com/questions/33529720/…
【解决方案2】:

您似乎没有在适配器中使用您的filteredData。 因此,当您调用notifiyDataSetChanged 时,用于填充ListView 的数据没有变化。

publishResults 方法应该更改用于填充视图的数据,即movieItems 列表。

private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();

        FilterResults results = new FilterResults();

        final List<Movie> list = originalMovieItems;

        int count = list.size();
        final ArrayList<Movie> nlist = new ArrayList<Movie>(count);

        String filterableString ;

        for (int i = 0; i < count; i++) {
            filterableString = list.get(i).getName();//or whatever you want to filter on
            if (filterableString.toLowerCase().contains(filterString)) {
                nlist.add(list.get(i));
            }
        }

        results.values = nlist;
        results.count = nlist.size();

        return results;
    }

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

}

所以为了保持电影列表不变(不是你显示的,而是你过滤的那个),你应该在你的适配器类中添加一个 originalMovieList 字段并修改构造函数,如下所示。

public CustomListAdapter(Activity activity, List<Movie> movieItems) {
     this.activity = activity;
     this.movieItems = movieItems;
     bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
      this.originalMovieList = movieItems;
         }

【讨论】:

  • 这么说他已经有方法做的很好了还不知道?
  • 我应该对 publishResults 方法进行哪些更改
  • protected void publishResults(CharSequence 约束,FilterResults 结果) { filteredData = (ArrayList) results.values; notifyDataSetChanged(); }
  • 我在方法中用 movieItems 替换了 filteredData,但它标记了错误。上帝知道我在这里迷路了。不知道具体要做什么。 hhhmmmmmmmmmmmm
  • 那是因为您应该将此行更改为nList.add(filterableString)nList.add(list.get(i))。这些版本的目标是让您的过滤器返回Movie 的列表,而不是String 的列表。所以你应该用Movie对象填充结果列表,而不是String
【解决方案3】:

这就是我能够解决搜索代码的痛苦的方法。

在我的 MainActivity

public class MainActivity extends Activity {

 private List<Movie> currentMovieList = new ArrayList<Movie>();
 private List<Movie> originalMovieList = new ArrayList<Movie>();
 private CustomListAdapter adapter;
 private ListView mList;
 // Search EditText
 EditText inputSearch;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_main);

inputSearch = (EditText) findViewById(R.id.inputSearch);

adapter = new CustomListAdapter(this, currentMovieList);
    mList.setAdapter(adapter);


    inputSearch.addTextChangedListener(new TextWatcher() {

        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text

            String filterString = cs.toString().toLowerCase();
            Log.e("TAG", "filterString:" + filterString);
            currentMovieList.clear();
            if (TextUtils.isEmpty(filterString)) {
                currentMovieList.addAll(originalMovieList);
            }

            String filterableString;
            for (Movie movie : originalMovieList) {

            //search from the title field
                if (movie.getTitle().toLowerCase().contains(filterString)) {
                    currentMovieList.add(movie);
                }
            //search from the year field
                else if (String.valueOf(movie.getYear()).toLowerCase().contains(filterString))
                {
                    currentMovieList.add(movie);
                }
            //search from the rating field
                else if (String.valueOf(movie.getRating()).toLowerCase().contains(filterString))
                {
                    currentMovieList.add(movie);
                }
            //search from the genre field
                else if (movie.getGenre().toString().toLowerCase().contains(filterString))
                {
                    currentMovieList.add(movie);
                }
            }
            adapter.notifyDataSetChanged();
            //FLAGS Cannot resolve method 'getFilter()' here
        }

        @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
        }
    });

} }

并将其添加到您的 CustomListAdapter

public class CustomListAdapter extends BaseAdapter implements Filterable {

    private Activity activity;
 private LayoutInflater inflater;

 private List<String>originalData = null;
 // private List<String>filteredData = null;

 private List<Movie> movieItems;
 private List<Movie> originalMovieList;
 private String[] bgColors;
 ImageLoader imageLoader = MyApplication.getInstance().getImageLoader();
 private ItemFilter mFilter = new ItemFilter();


 public CustomListAdapter(Activity activity, List<Movie> movieItems) {
       this.activity = activity;
        this.movieItems = movieItems;
      // this.originalMovieList = movieItems;
      this.originalMovieList = new ArrayList<Movie>(movieItems);
      bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
        }

    //Add Below Method
    public void reloadData(){
       this.originalMovieList = new ArrayList<Movie>(movieItems);
     notifyDataSetChanged();
        }
     @Override
 public int getCount() {
     return movieItems.size();
        }

 @Override
    public Object getItem(int location) {
        return movieItems.get(location);
        }

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

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

     if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.list_row_image, null);

    if (imageLoader == null)
        imageLoader = MyApplication.getInstance().getImageLoader();
    NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);

    TextView serial = (TextView) convertView.findViewById(R.id.serial);
    TextView title = (TextView) convertView.findViewById(R.id.title);
    TextView rating = (TextView) convertView.findViewById(R.id.rating);
    TextView genre = (TextView) convertView.findViewById(R.id.genre);
    TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

    // getting movie data for the row
    Movie m = movieItems.get(position);

    // thumbnail image
    thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

    // title
    title.setText(m.getTitle());

    // rating
    rating.setText("Rating: " + String.valueOf(m.getRating()));

     // genre
     String genreStr = "";
        for (String str : m.getGenre()) {
          genreStr += str + ", ";
     }
     genreStr = genreStr.length() > 0 ? genreStr.substring(0,
            genreStr.length() - 2) : genreStr;
        genre.setText(genreStr);

        // release year
     year.setText(String.valueOf(m.getYear()));

     String color = bgColors[position % bgColors.length];
        serial.setBackgroundColor(Color.parseColor(color));




      return convertView;
 }


            public Filter getFilter() {
                return mFilter;
            }

            private class ItemFilter extends Filter {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {

                    String filterString = constraint.toString().toLowerCase();

                    FilterResults results = new FilterResults();


                    //results.values = nlist;
                    //results.count = nlist.size();
                    results.values = originalMovieList;
                    results.count = originalMovieList.size();

                    return results;
                }

                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    //filteredData = (ArrayList<String>) results.values;
                    //movieItems = (ArrayList<Movie>) results.values;
                    movieItems.clear();
                    movieItems.addAll((ArrayList<Movie>) results.values);
                    notifyDataSetChanged();
                }

            }



}

现在这是一个 WRAP。感谢 @DhavalPatel 那家伙是 Android 大师。 He made all this happen。 -快乐编码

【讨论】:

  • @DhavalPatel 再次感谢。如果我回答正确,你可以投票给这个答案。 #wink
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 2020-03-02
相关资源
最近更新 更多