Android 使用 ListView 的项目点击时 Searchview 过滤错误

Android Searchview filtering wrong on item click with ListView

我尝试过其他解决方案。但问题对我来说是不同的。 我在我的应用程序中实现了 SearchViewListView。当我搜索某些内容时,数组的第一项打开 在项目单击 上。但我需要打开搜索中列出的相同项目。搜索结果过滤良好,但 onClick 项目给出了不同的项目。 请注意,我的问题是不同的,而不是重复的。 我的代码如下:


public class Searchpage extends AppCompatActivity {
    SearchView searchView;
    ListView listView;
    ArrayAdapter<String> adapter;


    String[] name = {
           "General Science", "Social Science", "Maths", "English", "Politics", "IT"
  };
    String[] file= {
           "science.pdf", "social.pdf", "maths.pdf", "english.pdf", "politics.pdf", it.pdf"
    };
    int[] pagenum = {
            0,0,0,0,0,0
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchpage);
        searchView = findViewById(R.id.srch);
        listView = findViewById(R.id.searchlist);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);
        listView.setAdapter(adapter);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                adapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent ij = new Intent(getApplicationContext(), PdfView.class);
                ij.putExtra("furl", "fl/" + pagenum[position]);
                ij.putExtra("pagenm", pagenum[position]);
                startActivity(ij);
            }
        });
    }


}

首先使用ArrayList代替array初始化ArrayAdapter

ArrayList<String> name = new ArrayList<>(Arrays.asList(
        "General Science", "Social Science", "Maths", "English", "Politics", "IT"
));

然后 使用下面的代码找出正确的 position 过滤数据

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    int actualPosition = name.indexOf(adapter.getItem(position));

    Intent ij = new Intent(getApplicationContext(), PdfView.class);
    ij.putExtra("furl", "fl/" + file[actualPosition]);
    ij.putExtra("pagenm", pagenum[actualPosition]);
    startActivity(ij);
}