带有SearchView的Android ListView,经过筛选的搜索结果不会直接指向正确的意图

问题描述 投票:1回答:1

首先,我是一个初学者,所以请在这里忍受一会儿。

我正在尝试创建包含项目列表的应用。当您单击该项目时,将转到一个新的相应活动。当我添加SearchView来过滤列表项时,单击过滤后的结果现在出现问题,它们不直接指向相应的活动。

您能否在下面更正我的代码,或者提供一种更好的方法来直接进行相应的活动。请提供尽可能详细的信息。提前非常感谢。

MainActivity.java

public class MainActivity extends Activity
        implements SearchView.OnQueryTextListener {

    private SearchView mSearchView;
    private ListView mListView;

    private final String[] mStrings = { "Google", "Apple", "Samsung", "Sony", "LG", "HTC" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

        setContentView(R.layout.activity_main);

        mSearchView = findViewById(R.id.search_view);
        mListView = findViewById(R.id.list_view);
        mListView.setAdapter(new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1,
                mStrings));
        mListView.setTextFilterEnabled(true);
        setupSearchView();
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    Intent i = new Intent(MainActivity.this, google.class);
                    startActivity(i);
                } else {
// code to direct to the corresponding activity                    
            }
        });
    }

    private void setupSearchView() {
        mSearchView.setIconifiedByDefault(false);
        mSearchView.setOnQueryTextListener(this);
        mSearchView.setSubmitButtonEnabled(true);
        mSearchView.setQueryHint("Search Here");
    }

    public boolean onQueryTextChange(String newText) {
        if (TextUtils.isEmpty(newText)) {
            mListView.clearTextFilter();
        } else {
            mListView.setFilterText(newText);
        }
        return true;
    }

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

}
android listview position searchview onitemclicklistener
1个回答
0
投票
if (position == 0) {
     Intent i = new Intent(MainActivity.this, google.class);
     startActivity(i);
} else if ( position == 1){
     // do something, sending to activity of choice
} else if ( position == 2){
     // do something , sending to activity of choice
}

针对您想要进行多少种不同的活动重复此操作。

© www.soinside.com 2019 - 2024. All rights reserved.