【问题标题】:SearchView back to search results implementationSearchView 返回搜索结果的实现
【发布时间】:2016-01-12 20:23:39
【问题描述】:

我的ActionBar 中有一个SearchView,用于过滤结果并显示在ListView 中。一旦用户单击一个项目,我就会启动一个新活动来显示该项目的详细信息。当他们点击后退按钮时,我想显示过滤后的搜索结果。他们输入的搜索词组保留在 SearchView 中。

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: android searchview


    【解决方案1】:

    在我的应用中,我有几种方法可以将搜索结果放入搜索结果活动中。如果搜索活动正在发送结果,我会在Intent extras 中检查结果。如果发生方向更改,我将使用 savedInstanceState 重新填充搜索结果,如果我导航到详细信息活动,然后再次返回,我会从保存的文件中重新填充搜索结果。所以我的onCreate() 代码的结构是这样的:

    if(savedInstanceState != null) {
        terms = savedInstanceState.getStringArrayList(TERM_RESULTS_KEY);
    } else {
        Bundle args = getIntent().getExtras();
        if(args != null) {
            resultsData = args.getParcelableArrayList(SearchActivity.SEARCH_RESULT_ARGS);
            //...
        } else {
            terms = getSavedResults();
        }
    }
    

    当我离开活动时(如您提到的转到详细信息页面),我会像这样保存搜索结果:

    private void saveResults(ArrayList<String> results) {
        try {
            FileOutputStream fileOutputStream = openFileOutput(SAVED_RESULTS_FILENAME, Context.MODE_PRIVATE);
            ObjectOutputStream out = new ObjectOutputStream(fileOutputStream);
            out.writeObject(results);
            out.close();
            fileOutputStream.close();
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    由于ArrayList 是可序列化的,因此使用ObjectOutputStream 写入磁盘非常容易。然后,当用户在您的详细信息活动中点击后退按钮时,您将检索以前的搜索结果,如下所示:

    @SuppressWarnings("unchecked")
    private ArrayList<String> getSavedResults() {
        ArrayList<String> savedResults = null;
    
        try {
            FileInputStream inputStream = openFileInput(SAVED_RESULTS_FILENAME);
            ObjectInputStream in = new ObjectInputStream(inputStream);
            savedResults = (ArrayList<String>) in.readObject();
            in.close();
            inputStream.close();
    
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    
        return savedResults;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多