繁体   English   中英

Android系统。 在RecyclerView中搜索和过滤

[英]Android. Search and filter in the RecyclerView

翻译使用“谷歌翻译”!

简要说明问题。 我决定尝试使用RecyclerView。 像搜索listView这样的现成解决方案,没有必要全部实现。 所以我找到了一个解决方案,如果在源代码的底部需要一个解决方案,但是存在问题。 有一个列表,它显示标题,当您点击第二个回合Activiti中已有标题和完整描述的任何项目时。 实现我喜欢:在MainActivity中我从数据库(使用Sugar ORM)头文件和id加载

ArrayList<String> arrTitle = new ArrayList<>();
for(Contact contact:allContacts){
arrTitle.add(contact.title);
}

ArrayList<String> arrId = new ArrayList<>();
for(Contact contact:allContacts){
long  i = contact.getId();
String str = Long.toString(i);
arrId.add(str);
}

然后将它们传送到适配器

mAdapter = new RecyclerAdapter(arrTitle,  arrId);

适配器Recycler Adapter我得到值推导标题到列表,第二个传递id活动

        @Override
public void onBindViewHolder(ViewHolder holder, int position) {

// Convert the id to the array
idTab = new String[mId.size()];
for (int i = 0; i != mId.size(); i++) {
    idTab[i] = mId.get(i);
}

// Element position
final int idvadaptere = position;
// Display headers RecyclerView
holder.mTextView.setText(mDataset.get(position));

holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Context context = v.getContext();
        Intent ddddd = new Intent(context, LastActivity.class);
        ddddd.putExtra("id", idTab[idvadaptere]);
        context.startActivity(ddddd);
    }
});
}

在第二个Activiti LastActivity中,我得到了id,并且在此id的基础上已经推断出文本字段中的值

// Get the Intent extract from it an object
// Extract from it an object
idString = intent.getStringExtra("id");
// Convert the id in number
idInt = Integer.parseInt(idString);


// Display the text fields
Contact title = Contact.findById(Contact.class, idInt);
String titleStr = title.title;
textView.setText(titleStr);

Contact prich = Contact.findById(Contact.class, idInt);
String prichStr = prich.prich;
textView2.setText(prichStr);

问题是,如果找到一个标题,这个列表的标题位置将不会是第五个,例如,第一个和id必须不同于第二个值aktiviti不公开第五个id,并且第一。 源搜索,如果您需要复制任何人,它可以正常工作,唯一的问题是通过单击列表项来传输数据。

activity_main.xml中

<android.support.v7.widget.SearchView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/search_view"
  android:layout_gravity="right"
  app:theme="@style/Theme.AppCompat.NoActionBar"
  app:searchIcon="@drawable/ic_search_white_24dp"/>

MainActivity.java

 private SearchView searchView;

在onCreate

searchView = (SearchView) findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String text) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String text) {
        mAdapter.filter(text);
        return false;
    }
});

RecyclerAdapter.java

private ArrayList<String> mDataset;
private ArrayList<String> mCleanCopyDataset;

构造函数

public RecyclerAdapter(ArrayList<String> dataset) {
mDataset = dataset;
mCleanCopyDataset = mDataset;
}

搜索

      // The filter () method we iterate through all the items on the list and if any item contains the search text, we add it to a new list mDataset:

public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
mDataset = new ArrayList<String>();
if (charText.length() == 0) {
    // mCleanCopyDataset we always contains the unaltered and the filter (full) copy of the list of data
    mDataset.addAll(mCleanCopyDataset);
} else {
    for (String item : mCleanCopyDataset) {

       // we iterate through all the items on the list and if any item contains the search text, we add it to a new list mDataset
        if (item.toLowerCase(Locale.getDefault()).contains(charText)) {
            mDataset.add(item);
        }
    }
}
// method notifyDataSetChanged () allows you to update the list on the screen after filtration
notifyDataSetChanged();
}

完整代码RecyclerAdapter.java

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

private ArrayList<String> mDataset;
private ArrayList<String> mId;
private ArrayList<String> mCleanCopyDataset;
String[] idTab;
String[] titleTab;

public static class ViewHolder extends RecyclerView.ViewHolder {
    public TextView mTextView;

    public ViewHolder(View v) {
        super(v);
        mTextView = (TextView) v.findViewById(R.id.tv_recycler_item);
    }
}

public RecyclerAdapter(ArrayList<String> dataset, String[] titleTab, ArrayList<String> id) {
    mDataset = dataset;
    titleTab = titleTab;
    mId = id;
    mCleanCopyDataset = mDataset;
}

@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                     int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.recycler_item, parent, false);


    ViewHolder vh = new ViewHolder(v);
    return vh;
}


@Override
public void onBindViewHolder(final ViewHolder holder, int position) {

    idTab = new String[mId.size()];
    for (int i = 0; i != mId.size(); i++) {
        idTab[i] = mId.get(i);
    }

     holder.mTextView.setText(mDataset.get(position));

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Context context = v.getContext();
            Intent ddddd = new Intent(context, LastActivity.class);
            ddddd.putExtra("id", idTab[holder.getAdapterPosition()]);
            context.startActivity(ddddd);
        }
    });
}


@Override
public int getItemCount() {
    return mDataset.size();
}



public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    mDataset = new ArrayList<String>();
    if (charText.length() == 0) {

        mDataset.addAll(mCleanCopyDataset);
    } else {
        for (String item : mCleanCopyDataset) {

            if (item.toLowerCase(Locale.getDefault()).contains(charText)) {
                mDataset.add(item);
            }
        }
    }
    notifyDataSetChanged();
}

}

在此输入图像描述

在此输入图像描述

您应该使用Android的内置功能来过滤回收站视图。

为此,请使您的RecyclerAdapter实现可过滤。

public class MyAdapter extends RecyclerVew.Adapter implements Filterable {

    private MyFilter filter;

    public MyAdapter() {
        // Do stuff
    }

    @Override
    public Filter getFilter() {
        if (filter == null) {
            filter = new MyFilter(this, getElements());
        }
        return filter;
    }

您会注意到在此代码示例中,我有一个名为MyFilter的东西。 这是您将创建并为其提供自定义逻辑的内容。

这只是一个例子。

private static class MyFilter extends Filter {

    private final MyAdapter adapter;
    private final List<String> originalList;
    private final List<String> filteredList;

    private MyFilter(MyAdapter adapter, List<String> originalList) {
        super();
        this.adapter = adapter;
        this.originalList = new LinkedList<>(originalList);
        this.filteredList = new ArrayList<>();
    }

    @Override
    protected FilterResults performFiltering(CharSequence charSequence) {
        filteredList.clear();
        final FilterResults results = new FilterResults();

        if (charSequence.length() == 0) {
            filteredList.addAll(originalList);
        } else {
            final String filterPattern = charSequence.toString().toLowerCase().trim();
            for (String item : originalList) {
                if (item.toLowerCase().contains(filterPattern) {
                    filteredList.add(item);
                }
            }
        }

        results.values = filteredList;
        results.count = filteredList.size();
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
        mDataset.clear();
        mDataset.add(filterResults.values);
        adapter.notifyDataSetChanged();
    }
}

然后在你的onQueryTextChange方法中,调用过滤器。

@Override
public boolean onQueryTextChange(String text) {
    mAdapter.getFilter().filter(text);
    return false;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM