RecyclerView搜索过滤器在过滤结果后位置错误

时间:2019-05-30 17:19:39

标签: java android android-recyclerview searchview

你好朋友请帮我,我正在使用Recylerview并实现了searchfilter,但问题是,当我单击item时,在recylerview中搜索该项目后,它总是返回该项目的0位置,我想要列表项的实际位置,请在这里提供帮助我的代码在recylerview中搜索项目后如何获得实际位置recylerview

这是我的代码

package bible.swordof.God;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
    private ListView listView;
    private ArrayList<String> books;
    private ArrayList<String> bookid;
    private ListViewAdapter adapter;
    private DatabaseHelper mDBHelper = null;
    private SQLiteDatabase mDb = null;
    BookRecyclerAdopter bookRecyclerAdopter;

//life is awesome

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        setData();
        RecyclerView bookanme = findViewById(R.id.list);
        bookanme.setLayoutManager(new LinearLayoutManager(this));

    bookRecyclerAdopter = new BookRecyclerAdopter(this, books);

        bookanme.setAdapter(bookRecyclerAdopter);



        /*    adapter = new ListViewAdapter(MainActivity.this, R.layout.item_listview, books, bookid);
        listView.setAdapter(adapter);*/







        /* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                 int booknumber=position;
                 String  bookname=bookid.get(position);





                Toast.makeText(MainActivity.this, ""+bookname, Toast.LENGTH_SHORT).show();

             *//*   Intent intent=new Intent(MainActivity.this,Chapters.class);
                intent.putExtra("booknumber",booknumber);

                intent.putExtra("bookname",bookname);

                startActivity(intent);*//*



            }
        });
    }

*/
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.search_voice_btn:
                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(intent, 10);
                } else {
                    Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
                }


                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 10:
                if (resultCode == RESULT_OK && data != null) {

                    ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);


                    Toast.makeText(this, "" + result.get(0), Toast.LENGTH_SHORT).show();


                }
                break;
        }
    }

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

        MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(myActionMenuItem);

        searchView.setOnQueryTextListener(this);

        return true;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        Fragment fragment;
        int id = item.getItemId();


        if (id == R.id.home) {

            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);

        } else if (id == R.id.favoruite) {
            Intent intent = new Intent(this, Favourite.class);

            startActivity(intent);
        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void setData() {


        books = new ArrayList<>();
        bookid = new ArrayList<>();

        mDBHelper = new DatabaseHelper(this);
        mDb = mDBHelper.getReadableDatabase();

        Cursor cursor = mDb.rawQuery("select b,n from key_english", new String[]{});


        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                do {
                    books.add(cursor.getString(1));
                    bookid.add(cursor.getString(0));

                } while (cursor.moveToNext());
            }
        }
    }


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

    @Override
    public boolean onQueryTextChange(String newtext) {

        String userinput = newtext.toLowerCase();
        List<String> newlist = new ArrayList<>();
        for (String name : books) {

            if (name.toLowerCase().contains(userinput)) {

                newlist.add(name);


            }


        }

        bookRecyclerAdopter.updatelist(newlist);
        return true;

    }

}




package bible.swordof.God;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
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 com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;

import java.util.ArrayList;
import java.util.List;

public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{

    private List<String> bookname;

Context context;

    public BookRecyclerAdopter(Context context,List<String> bookname) {
        this.bookname = bookname;
        this.context=context;

    }



    public class Booksholder extends RecyclerView.ViewHolder {
        private ImageView imageView;
        private TextView bookname;

        public Booksholder(@NonNull View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.image_view);
            bookname = (TextView) itemView.findViewById(R.id.text);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {



                }
            });
        }
    }


    @Override
    public Booksholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View view = inflater.inflate(R.layout.item_listview, viewGroup, false);


        return new Booksholder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull Booksholder booksholder, final int i) {
        booksholder.bookname.setText(bookname.get(i));

        //get first letter of each String item
        String firstLetter = String.valueOf(bookname.get(i).charAt(0));




        ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
        // generate random color
        int color = generator.getColor(bookname.get(i));

        TextDrawable drawable = TextDrawable.builder()
                .buildRound(firstLetter, color); // radius in px



        booksholder.imageView.setImageDrawable(drawable);




    }



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

public  void  updatelist(List<String>newlist){
        bookname=new ArrayList<>();
        bookname.addAll(newlist);
        notifyDataSetChanged();
}

}

2 个答案:

答案 0 :(得分:0)

您将需要维护一个单独的书名列表。我们称之为filteredBookname。最初将其设置为bookname

public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{

    private List<String> bookname;
    private List<String> filteredBookname;

Context context;

    public BookRecyclerAdopter(Context context,List<String> bookname) {
        this.bookname = bookname;
        this.filteredBookname = bookname
        this.context=context;

    }
...
// other pieces of code.

,而不是使用bookname来填充RecyclerView项,而是使用filteredBookname

,您的更新列表方法将是

public  void  updatelist(List<String>newlist){
        filteredBookname=new ArrayList<>();
        filteredBookname.addAll(newlist);
        notifyDataSetChanged();
}

使用上述方法,您始终可以在原始列表bookname中找到您商品的正确位置

答案 1 :(得分:0)

原因是您选择了错误的列表,请从过滤后的适配器列表/模型中选择您的数据。

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Books booksdata= (Books)adapterName.bookname.get(position);
            Toast.makeText(MainActivity.this, ""+booksdata.bookname, Toast.LENGTH_SHORT).show();
            Intent intent=new Intent(MainActivity.this,Chapters.class);
            intent.putExtra("booknumber",booksdata.booknumber);
            intent.putExtra("bookname",booksdata.bookname);
            startActivity(intent);
        }
    });
}