在recyclerview中使用过滤方法的自动填充选项

时间:2017-07-17 11:52:29

标签: android search filter android-recyclerview android-cardview

在我的应用程序中,我使用cardview实现了recyclerview,以显示公司内部员工的列表。现在我想实现一个serch选项,用户可以使用该选项搜索员工的姓名。我已经在网站上阅读了相关文档。我写了一个代码来实现一个serch选项。但不幸的是,我可以看到搜索选项,我可以写它,但它无法检测列表中的名称。我不知道我的代码中有什么问题。这是我的适配器类,其中我实现了Filterable mehtod

public class MyColleaguesAdapter extends RecyclerView.Adapter<MyColleaguesAdapter.ColleagueHolder> implements Filterable {

private static final String TAG = "MyColleaguesAdapter";
protected List<MyColleageModel> colleagueObject;
protected List<MyColleageModel> filteredcolleague;
private Context context;

public MyColleaguesAdapter(List<MyColleageModel> colleagueObject, Context context) {

    this.colleagueObject = colleagueObject;
    this.filteredcolleague=colleagueObject;
    this.context = context;
}

@Override
public ColleagueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view= LayoutInflater.from(parent.getContext())
            .inflate(R.layout.colleage_row_layout,parent,false);
    return new ColleagueHolder(view);
}

@Override
public void onBindViewHolder(ColleagueHolder holder, int position) {
    final MyColleageModel myColleague=colleagueObject.get(position);

    holder.name.setText(myColleague.getName());
    holder.company.setText(myColleague.getCompany());
    holder.title.setText(myColleague.getTitle());

    holder.cardView.setTag(position);
    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int pos = (int)view.getTag();
            openDetailActivity(myColleague.getMobile(),myColleague.getMail(), myColleague.getName(),
                    myColleague.getCompany(), myColleague.getDepartment(), myColleague.getTitle());

        }
    });
}

@Override
public int getItemCount() {
    return colleagueObject.size();
}
//open activity
private void openDetailActivity(String...details)
{
    Intent i=new Intent(context,DetailMyColleague.class);
    i.putExtra("mail",details[1]);
    ........
    context.startActivity(i);
}

@Override
public Filter getFilter() {
    return new Filter() {
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredcolleague = (List<MyColleageModel>) results.values;
            MyColleaguesAdapter.this.notifyDataSetChanged();

        }
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<MyColleageModel> filteredResults = null;
            if (constraint.length() == 0) {
                filteredResults = colleagueObject;
            } else {
                filteredResults = getFilteredResults(constraint.toString().toLowerCase());
            }

            FilterResults results = new FilterResults();
            results.values = filteredResults;

            return results;
        }
     };
 }
protected List<MyColleageModel> getFilteredResults(String constraint) {
    List<MyColleageModel> results = new ArrayList<>();

    for (MyColleageModel item : colleagueObject) {
        if (item.getName().toLowerCase().contains(constraint)) {
            results.add(item);
            Log.d( TAG,"value is here "+item.getName());
        }
    }
    return results;
}

public class ColleagueHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    public CardView cardView;
    public TextView name;
    public TextView company;
    public TextView title;

    public ColleagueHolder(View itemView) {
        super(itemView);
        name=(TextView) itemView.findViewById(R.id.colleague_name);
        company=(TextView)itemView.findViewById(R.id.company_name);
        title=(TextView) itemView.findViewById(R.id.job_role);
        cardView=(CardView)itemView.findViewById(R.id.cvSingleUser);
    }
   }

这是我的MainActivity

 public class MyColleaguesPage extends AppCompatActivity implements SearchView.OnQueryTextListener{

private RecyclerView recyclerView;
private CardView cardView;
private MyColleaguesAdapter adapter;
private List<MyColleageModel> colleagueObject;
InputStream is;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mycolleagues_layout);

    // Showing and Enabling clicks on the Home/Up button
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    cardView=(CardView)findViewById(R.id.cvSingleUser);
    recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MyColleaguesPage.this);
    recyclerView.setLayoutManager(layoutManager);
    new JSONTask().execute();

}

 @Override
 public boolean onQueryTextSubmit(String query) {
    return false;
 }

 @Override
 public boolean onQueryTextChange(String newText) {
      List<MyColleageModel> filteredModelList = filter(colleagueObject, newText);

    if (filteredModelList.size() > 0) {
        //myPhotosAdapter.setFilter(filteredModelList);
        return true;
    } else {
        Toast.makeText(MyColleaguesPage.this, "Not Found", Toast.LENGTH_SHORT).show();
        return false;
    }
 }


  public class JSONTask extends AsyncTask<String, String, List<MyColleageModel>> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<MyColleageModel> doInBackground(String... params) {

        colleagueObject = new ArrayList<MyColleageModel>();

        try {
            //withou Gson
            JSONObject obj = new JSONObject(loadJSONFromAsset());
            JSONArray m_jArry = obj.getJSONArray("contacts");

            MyColleageModel my_clg;

            for (int i = 0; i < m_jArry.length(); i++) {
                JSONObject jo_inside = m_jArry.getJSONObject(i);
                String val1 = jo_inside.getString("mobile");
                String val2 = jo_inside.getString("mail");
                String val3 = jo_inside.getString("name");
                String val4 = jo_inside.optString("company");
                String val5 = jo_inside.optString("department");
                String val6 = jo_inside.optString("title");
                my_clg = new MyColleageModel(val1, val2, val3, val4, val5, val6);

                colleagueObject.add(my_clg);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onPostExecute(final List<MyColleageModel> result) {
        super.onPostExecute(result);

            adapter = new MyColleaguesAdapter(colleagueObject, getApplicationContext());
            recyclerView.setAdapter(adapter);

            adapter.notifyDataSetChanged();

    }
}

private String loadJSONFromAsset() {
   ....

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.recyclerviewmenu, menu);

    final MenuItem search = menu.findItem(R.id.search);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
    searchView.setOnQueryTextListener(this);
    return true;
}


private List<MyColleageModel> filter(List<MyColleageModel> models, String query) {
    query = query.toLowerCase();

    final List<MyColleageModel> filteredModelList = new ArrayList<>();

    for (MyColleageModel model : models) {
        final String text = model.getName().toLowerCase().toString();
        if (text.contains(query)) {
            filteredModelList.add(model);

        }
    }

    // arraylist in your adapter
    adapter = new MyColleaguesAdapter(colleagueObject, getApplicationContext());
    recyclerView.setAdapter(adapter);

    adapter.notifyDataSetChanged();

    return filteredModelList;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == android.R.id.home) {
        finish();
    }

    return super.onOptionsItemSelected(item);
}

}

这是我的recyclerviewmenu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context="myColleagues.MyColleaguesPage">

<item
    android:id="@+id/search"
    android:icon="@drawable/ic_search"
    android:title="Search"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

我的代码中没有收到错误。

2 个答案:

答案 0 :(得分:1)

遵循此规定

第1步在youractivity中实现SearchView.OnQueryTextListener

onCreateOptionsMenu中的

第2步写下以下代码

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

    final MenuItem item = menu.findItem(R.id.menu_search_album);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
    searchView.setOnQueryTextListener(this);
    return true;
}

第3步onQueryTextChange()方法

中写下此内容
@Override
public boolean onQueryTextChange(String newText) {

     List<MyColleageModel> filteredModelList = filter(data_fieldses, newText);

    if (filteredModelList.size() > 0) {
       //myPhotosAdapter.setFilter(filteredModelList);
        return true;
    } else {
        Toast.makeText(MyPhotosActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
        return false;
    }

}

第4步

    private List<MyColleageModel> filter(List<MyColleageModel> models, String query) {
    query = query.toLowerCase();

    final List<MyColleageModel> filteredModelList = new ArrayList<>();

    for (MyColleageModel model : models) {
        final String text = model.getImagename().toLowerCase().toString();
        if (text.contains(query)) {
            filteredModelList.add(model);

        }
    }

      // arraylist in your adapter
    myPhotosAdapter = new MyPhotosAdapter( MyPhotosActivity.this, (ArrayList<MyColleageModel>) filteredModelList);
    recyclerViewMyPhotos.setLayoutManager(new GridLayoutManager(MyPhotosActivity.this, 2));
    recyclerViewMyPhotos.setAdapter(myPhotosAdapter);
    myPhotosAdapter.notifyDataSetChanged();
    return filteredModelList;
}

在有任何疑问时问我

答案 1 :(得分:1)

IMO你在onPostExecute()中错过了setNotifyDatachaged()尝试上面的代码

    public class MyColleaguesPage extends AppCompatActivity{

private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private List<MyColleageModel> colleagueObject;
InputStream is;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mycolleagues_layout);

    // Showing and Enabling clicks on the Home/Up button
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MyColleaguesPage.this);
    recyclerView.setLayoutManager(layoutManager);

     adapter = new MyColleaguesAdapter(colleagueObject, getApplicationContext());
            recyclerView.setAdapter(adapter);
    new JSONTask().execute();

}



public class JSONTask extends AsyncTask<String, String, List<MyColleageModel>> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<MyColleageModel> doInBackground(String... params) {

        colleagueObject = new ArrayList<MyColleageModel>();

        try {
            //withou Gson
            JSONObject obj = new JSONObject(loadJSONFromAsset());
            JSONArray m_jArry = obj.getJSONArray("contacts");
            // ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
           // HashMap<String, String> m_li;

            MyColleageModel my_clg;

            for (int i = 0; i < m_jArry.length(); i++) {
                JSONObject jo_inside = m_jArry.getJSONObject(i);
                //my_clg=new MyColleageModel();
                String val1 = jo_inside.getString("mobile");
                String val2 = jo_inside.getString("mail");
                String val3 = jo_inside.getString("name");
                String val4 = jo_inside.optString("company");
                String val5 = jo_inside.optString("department");
                String val6 = jo_inside.optString("title");
                my_clg = new MyColleageModel(val1, val2, val3, val4, val5, val6);

                colleagueObject.add(my_clg);
            }



        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onPostExecute(final List<MyColleageModel> result) {
        super.onPostExecute(result);

            adapter.notifyDataSetChanged();
       }
   }

 private String loadJSONFromAsset() {
    ...........
 }
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.recyclerviewmenu, menu);

    MenuItem search = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
    search(searchView);
    return true;
}

private void search(SearchView searchView) {
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            adapter.getFilter().filter(newText);
            return true;
        }
    });
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        finish();
    }

    return super.onOptionsItemSelected(item);
}