Recyclerview搜索过滤在Android上不起作用。

huangapple go评论72阅读模式
英文:

Recyclerview Search Filter not working android

问题

以下是您提供的代码的中文翻译部分:

我的标题来自于 Retrofit当我在 SearchView 中输入任何内容时它不显示任何结果或建议以下是截图链接
[查看图像描述][1]

我参考了这篇博客https://velmm.com/android-recyclerview-search-filter-example/

非常感谢您提前的帮助

搜索活动

```java
public class Search extends AppCompatActivity {
    SearchView searchView;
    RecyclerView recyclerView;
    SearchAdapter slAdapter;
    List<StartLearning.SlModel> movieList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        // ...(略)
    }

    // ...(略)

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // ...(略)
    }

    // ...(略)

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        // ...(略)
    }

    @Override
    public void onBackPressed() {
        // ...(略)
    }
}

搜索适配器:

public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.CustomViewHolder> implements Filterable {

    List<StartLearning.SlModel> Slmdel;
    List<StartLearning.SlModel> Slmdel1;
    Context context;

    public SearchAdapter() {
        // ...(略)
    }

    // ...(略)

    @Override
    public SearchAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // ...(略)
    }

    @Override
    public void onBindViewHolder(SearchAdapter.CustomViewHolder holder, int position) {
        // ...(略)
    }

    @Override
    public int getItemCount() {
        // ...(略)
    }

    @Override
    public Filter getFilter() {
        // ...(略)
    }

    public class CustomViewHolder extends RecyclerView.ViewHolder {
        public TextView employeeName;
        TextView textView;

        public CustomViewHolder(View view) {
            // ...(略)
        }
    }
}

StartLearning.SlModel:

public class SlModel {
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("title")
    @Expose
    private String title;

    public SlModel(String id, String title) {
        this.id = id;
        this.title = title;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "SlModel{" +
                "title='" + title + '\'' +
                '}';
    }
}

希望这些翻译对您有所帮助!如果您需要更多信息或有其他问题,请随时提问。

英文:

My title is coming from retrofit.when I type anything in searchview it doesnt show any result/Suggestion when typed. here is the ss ---> enter image description here

im referring this blog --> https://velmm.com/android-recyclerview-search-filter-example/

help will be appreciated...thanks in advance

Search activity:

public class Search extends AppCompatActivity {
SearchView searchView;
RecyclerView recyclerView;
SearchAdapter slAdapter;
List&lt;StartLearning.SlModel&gt; movieList;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    searchView=findViewById(R.id.searchView);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
    searchView.onActionViewExpanded();
    searchView.setIconified(true);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    slAdapter = new SearchAdapter();
    recyclerView.setAdapter(slAdapter);

    movieList = new ArrayList&lt;&gt;();
  
    SLApiSevice service = SLApiClient.getRetrofitInstance().create(SLApiSevice.class);
    retrofit2.Call&lt;List&lt;StartLearning.SlModel&gt;&gt; call = service.getMySlmodel();

    call.enqueue(new Callback&lt;List&lt;StartLearning.SlModel&gt;&gt;() {
        @Override
        public void onResponse(retrofit2.Call&lt;List&lt;StartLearning.SlModel&gt;&gt; call, Response&lt;List&lt;StartLearning.SlModel&gt;&gt; response) {
            movieList = response.body();
            Log.d(&quot;TAG&quot;,&quot;Response = &quot;+movieList);
            slAdapter.setMovieList(getApplicationContext(),movieList);

        }

        @Override
        public void onFailure(retrofit2.Call&lt;List&lt;StartLearning.SlModel&gt;&gt; call, Throwable t) {
            Log.d(&quot;TAG&quot;,&quot;Response = &quot;+t.toString());



        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu1, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchView = (SearchView) menu.findItem(R.id.action_search)
            .getActionView();
    searchView.setSearchableInfo(searchManager
            .getSearchableInfo(getComponentName()));
    searchView.setMaxWidth(Integer.MAX_VALUE);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            slAdapter.getFilter().filter(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String query) {
            slAdapter.getFilter().filter(query);
            return false;
        }
    });
    return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId() ==android.R.id.home) {
        finish();
    }
    return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
    super.onBackPressed();
}}

Search Adapter

public class SearchAdapter extends RecyclerView.Adapter&lt;SearchAdapter.CustomViewHolder&gt; implements Filterable {

List&lt;StartLearning.SlModel&gt; Slmdel;
List&lt;StartLearning.SlModel&gt; Slmdel1;

Context context;

public SearchAdapter() {
}

public void setMovieList(Context context, final List&lt;StartLearning.SlModel&gt; movieList){
    this.context = context;
    if(this.Slmdel == null){
        this.Slmdel = movieList;
        this.Slmdel1 = movieList;
        notifyItemChanged(0, Slmdel1.size());
    } else {
        final DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {
            @Override
            public int getOldListSize() {
                return SearchAdapter.this.Slmdel.size();
            }

            @Override
            public int getNewListSize() {
                return movieList.size();
            }

            @Override
            public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
                return SearchAdapter.this.Slmdel.get(oldItemPosition).getTitle() == movieList.get(newItemPosition).getTitle();
            }

            @Override
            public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {

                StartLearning.SlModel newMovie = SearchAdapter.this.Slmdel.get(oldItemPosition);

                StartLearning.SlModel oldMovie = movieList.get(newItemPosition);

                return newMovie.getTitle() == oldMovie.getTitle() ;
            }
        });
        this.Slmdel = movieList;
        this.Slmdel1 = movieList;
        result.dispatchUpdatesTo(this);
    }
}

public SearchAdapter(Context context,List&lt;StartLearning.SlModel&gt; employees) {
    this.Slmdel = employees;
    this.context=context;
}

@Override
public SearchAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.startlearning_item, parent, false);

    return new SearchAdapter.CustomViewHolder(itemView);
}

@Override
public void onBindViewHolder(SearchAdapter.CustomViewHolder holder, int position) {

    holder.textView.setText(String.valueOf(position+1)+&quot;. &quot;);
    holder.employeeName.setText(Slmdel.get(position).getTitle());


}

@Override
public int getItemCount() {
    if(Slmdel != null){
        return Slmdel1.size();
    } else {
        return 0;
    }

}
@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            String charString = charSequence.toString();
            if (charString.isEmpty()) {
                Slmdel1 = Slmdel;
            } else {
                List&lt;StartLearning.SlModel&gt; filteredList = new ArrayList&lt;&gt;();
                for (StartLearning.SlModel movie : Slmdel) {
                    if (movie.getTitle().toLowerCase().contains(charString.toLowerCase())) {
                        filteredList.add(movie);
                    }
                }
                Slmdel1 = filteredList;
            }

            FilterResults filterResults = new FilterResults();
            filterResults.values = Slmdel1;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            Slmdel1 = (ArrayList&lt;StartLearning.SlModel&gt;) filterResults.values;

            notifyDataSetChanged();
        }
    };
}



public class CustomViewHolder extends RecyclerView.ViewHolder {
    public TextView employeeName;
    TextView textView;

    public CustomViewHolder(View view) {
        super(view);
        employeeName = (TextView) view.findViewById(R.id.Sl2);
        textView=view.findViewById(R.id.Sl1);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(context, NextSLactivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(&quot;title&quot;, Slmdel.get(getAdapterPosition()).getTitle());
                intent.putExtra(&quot;idSLnext&quot;, Slmdel.get(getAdapterPosition()).getId());
                //Log.e(&quot;ashwini&quot;,WAmdel.get(getAdapterPosition()).getId());
                context.startActivity(intent);

            }
        });


    }
}

}

List<StartLearning.SlModel>:

public class SlModel

{
    @SerializedName(&quot;id&quot;)
    @Expose
    private String id;
    @SerializedName(&quot;title&quot;)
    @Expose
    private String title;

    public SlModel(String id, String title) {
        this.id = id;
        this.title = title;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return &quot;SlModel{&quot; +
                &quot;title=&#39;&quot; + title + &#39;\&#39;&#39; +
                &#39;}&#39;;
    }
}}

答案1

得分: 1

package zon.searchview.com;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.viewHolder> implements Filterable {

    Context context; 
    ArrayList<ItemModel> arrayList, arrayListFiltered; 
    
    public CustomAdapter(Context context, ArrayList<ItemModel> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
        this.arrayListFiltered = arrayList;
    }

    @Override
    public viewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_list, viewGroup, false);
        return new viewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(viewHolder viewHolder, int position) {
        viewHolder.name.setText(arrayListFiltered.get(position).getName());
        viewHolder.image.setImageResource(arrayListFiltered.get(position).getImage());
    }
    
    @Override
    public int getItemCount() {
        return arrayListFiltered.size();
    }

    public class viewHolder extends RecyclerView.ViewHolder {
        TextView name;
        ImageView image;
        
        public viewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.name);
            image = (ImageView) itemView.findViewById(R.id.image);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, arrayListFiltered.get(getAdapterPosition()).getName(), Toast.LENGTH_LONG).show();
                }
            });
        }
    }
    
    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                
                ArrayList<ItemModel> arrayListFilter = new ArrayList<ItemModel>();
                
                if (constraint == null || constraint.length() == 0) {
                    results.count = arrayList.size();
                    results.values = arrayList;
                } else {
                    for (ItemModel itemModel : arrayList) {
                        if (itemModel.getName().toLowerCase().contains(constraint.toString().toLowerCase())) {
                            arrayListFilter.add(itemModel);
                        }
                    } 
                    results.count = arrayListFilter.size();
                    results.values = arrayListFilter;
                }
                return results;
            }
           
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                arrayListFiltered = (ArrayList<ItemModel>) results.values;
                notifyDataSetChanged();
                
                if (arrayListFiltered.size() == 0) {
                    Toast.makeText(context, "Not Found", Toast.LENGTH_LONG).show();
                }
            }
        };
        return filter;
    }
}
英文:
package zon.searchview.com;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter&lt;CustomAdapter.viewHolder&gt; implements Filterable {
Context context; 
ArrayList&lt;ItemModel&gt; arrayList,arrayListFiltered; 
public CustomAdapter(Context context, ArrayList&lt;ItemModel&gt; arrayList) {
this.context = context;
this.arrayList = arrayList;
this.arrayListFiltered = arrayList;
}
@Override
public  viewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_list, viewGroup, false);
return new viewHolder(view);
}
@Override
public  void onBindViewHolder(viewHolder viewHolder, int position) {
viewHolder.name.setText(arrayListFiltered.get(position).getName());
viewHolder.image.setImageResource(arrayListFiltered.get(position).getImage());
}
@Override
public int getItemCount() {
return arrayListFiltered.size();
}
public class viewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView image;
public viewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
image = (ImageView) itemView.findViewById(R.id.image);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context,arrayListFiltered.get(getAdapterPosition()).getName(),Toast.LENGTH_LONG).show();
}
});
}
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList&lt;ItemModel&gt; arrayListFilter = new ArrayList&lt;ItemModel&gt;();
if(constraint == null|| constraint.length() == 0) {
results.count = arrayList.size();
results.values = arrayList;
} else {
for (ItemModel itemModel : arrayList) {
if(itemModel.getName().toLowerCase().contains(constraint.toString().toLowerCase())) {
arrayListFilter.add(itemModel);
}
} 
results.count = arrayListFilter.size();
results.values = arrayListFilter;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListFiltered = (ArrayList&lt;ItemModel&gt;) results.values;
notifyDataSetChanged();
if(arrayListFiltered.size() == 0) {
Toast.makeText(context, &quot;Not Found&quot;, Toast.LENGTH_LONG).show();
}
}
};
return filter;`enter code here`
}
}

For more visit this:- https://www.11zon.com/zon/android/filter-recyclerview-with-searchview.php

huangapple
  • 本文由 发表于 2020年1月3日 22:36:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定