简体   繁体   English

使用 EditText 在 RecyclerView 中搜索

[英]Search in RecyclerView with EditText

I write this code for search in recyclerview with edit text but, when I run the application and input a text that I need to search about it on the edit text in the first letter the recycler content not changed and when I input the second Letter the RecyclerView become empty.我编写此代码以在带有编辑文本的 recyclerview 中进行搜索但是,当我运行应用程序并输入我需要在第一个字母的编辑文本上搜索它的文本时,回收站内容没有改变,当我输入第二个字母时RecyclerView 变空了。 how can I filter the recycler?我怎样才能过滤回收站? what is the wrong in my code?我的代码有什么问题? xml code:代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FamilyActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/search"
            android:layout_width="294dp"
            android:layout_height="70dp"
            android:layout_marginTop="-20dp"
            android:hint="Search ..."
            android:drawableLeft="@drawable/ic_search_black_24dp"
            />

        <Button
            android:id="@+id/add"
            android:layout_width="54dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="35dp"
            android:drawableTop="@drawable/ic_person_add_black_24dp"
            android:onClick="add_new_family"
            tools:ignore="OnClick" />
    </LinearLayout>



    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"


        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="50dp"></android.support.v7.widget.RecyclerView>

</RelativeLayout>

code in main activity:主要活动中的代码:

public class FamilyActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    FamilyAdapter familyAdapter;
    Button add_family;
    EditText search;

    List<Family> familyList;
    String patientID = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_family);
        add_family=(Button)findViewById(R.id.add);
        search =(EditText)findViewById(R.id.search);

        familyList = new ArrayList<>();
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            patientID = extras.getString("ID");
        }
        loadFamilyList();
        //adding some items to our list

        //creating recyclerView adapter
        FamilyAdapter adapter = new FamilyAdapter(this, familyList);

        //setting adapter to recyclerView
        recyclerView.setAdapter(adapter);

        addTextListener();

    }

public void addTextListener(){

        search.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {}

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence query, int start, int before, int count) {

                query = query.toString().toLowerCase();

                final List<Family> filteredList = new ArrayList<>();

                for (int i = 0; i < familyList.size(); i++) {

                    final String text = familyList.get(i).toString().toLowerCase();
                    if (text.contains(query)) {

                        filteredList.add(familyList.get(i));
                    }
                }

                recyclerView.setLayoutManager(new LinearLayoutManager(FamilyActivity.this));
                FamilyAdapter fadapter = new FamilyAdapter(FamilyActivity.this,filteredList);
                recyclerView.setAdapter(fadapter);
                fadapter.notifyDataSetChanged();  // data set changed
            }
        });
    }

code in adapter:适配器中的代码:

public class FamilyAdapter extends RecyclerView.Adapter<FamilyAdapter.FamilyViewHolder> {

private Context context;
private List<Family> familyList;
private List<Family> familyListFull;

public FamilyAdapter(Context context, List<Family> familyList) {
    this.context = context;
    this.familyList = familyList;
    familyListFull=new ArrayList<>(familyList);
}

@NonNull
@Override
public FamilyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.list_layout, null);
    return new FamilyViewHolder(view);

}

@Override
public void onBindViewHolder(FamilyViewHolder familyViewHolder, final int position) {
    Family family = familyList.get(position);
    familyViewHolder.textViewTitle.setText(family.getName());
    familyViewHolder.familyLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: clicked on : " + familyList.get(position));
            String name = familyList.get(position).getName();
            String num = familyList.get(position).getNum();
            Intent intent = new Intent(context, Chatting.class);
            intent.putExtra("num", num);
            intent.putExtra("name", name);
            context.startActivity(intent);


        }
    });
    familyViewHolder.deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(context );
            builder.setTitle("Delete");
            builder.setMessage("Are you sure you want to delete this one ")
                    .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            RemoveFamilyMember(position);
                        }
                    }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    builder.setCancelable(true);
                }
            });
            AlertDialog alert=builder.create();
            alert.show();


        }
    });


}

you can try something like this I think this might work, I haven't tested it but I think that making a new adapter everytime that the edittext has something in it is a bad idea.你可以尝试这样的事情我认为这可能有效,我没有测试过但我认为每次编辑文本中有东西时制作一个新的适配器是一个坏主意。 and if you get to the point back to where the query is equal to "" empty string then you should make the fileterd list back into the whole list which I didn't put in there如果您回到查询等于“”空字符串的位置,那么您应该将 fileterd 列表放回到我没有放在那里的整个列表中

public class FamilyActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    FamilyAdapter familyAdapter;
    Button add_family;
    EditText search;

    List<Family> familyList;
    List<Family> filteredList;
    String patientID = "";
    FamilyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_family);
        add_family=(Button)findViewById(R.id.add);
        search =(EditText)findViewById(R.id.search);

        familyList = new ArrayList<>();
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            patientID = extras.getString("ID");
        }
        loadFamilyList();
        filteredList = new ArrayList<>(familyList);
        //adding some items to our list

        //creating recyclerView adapter
        adapter = new FamilyAdapter(this, filteredList);

        //setting adapter to recyclerView
        recyclerView.setAdapter(adapter);

        addTextListener();

    }

public void addTextListener(){

        search.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {}

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence query, int start, int before, int count) {

                query = query.toString().toLowerCase();

                filteredList = new ArrayList<>();

                for (int i = 0; i < familyList.size(); i++) {

                    final String text = familyList.get(i).toString().toLowerCase();
                    if (text.contains(query)) {

                        filteredList.add(familyList.get(i));
                    }
                }
                                    recyclerView.removeAllViews();;
                                    adapter.notifyDataSetChanged();  // data set changed
            }
        });
    }
editTextSearch.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) {
            filter(s.toString());

        }
    });
private void filter(String text) {
    ArrayList<Model> newList = new ArrayList<>();
    for (Model item : mModelList) {
        if (item.getTitle().contains(text)){
            newList.add(item);
        }
    }
    yourAdapter.setFilter(newList);
}

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

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