文件管理器中的文件搜索功能:

描述:输入一个字符串,搜索给定目录下的所有包含搜索字符的目录或文件。

1. 算法实现
分析:文件管理器中的文件层次结构是一颗树结构,该问题就是搜索树的除了根节点外,所有包含给定字符的结点,其中目录相当于非叶节点,文件相当于叶子结点。
实现:记目标路径为root,搜索字符为searchString。使用队列,依次扫描它的儿子结点,如果包含searchString,则添加到输出结果中;如果儿子结点为非叶结点,则添加到队列当中;
在一轮循环的最后,从队列中取出首元素,进入下一次循环。

public void searchProcess(File root,ArrayList<String> pathItems, String searchString){
    if(root == null || !root.exist() || !root.isDirectory()) {
        pathItems = null;
    }

    ArrayDeque<File> queueFiles = new ArrayDeque<File>();
    File top = root;
    while(top != null) {
        File[] files = top.listFiles();
        if(files != null) {
            for(File f : files){
                if (f.getName().length() >= 1 && f.getName().charAt(0) == '.') {
                    continue;
                }
                if (f.getName().toLowerCase().contains(query.toLowerCase())) {
                    pathItems.add(f.getPath);
                }
                if(f.isDirectory()) {
                    queueFiles.add(f);
                }
            }
        }

        try {
            top = queueFiles.remove();
            // Log.i(TAG,"top=="+top);
        } catch (NoSuchElementException e) {
            e.printStackTrace();
            top = null;
        }
    }
    
    if (pathItems != null) {
        Collections.sort(pathItems,String.CASE_INSENSITIVE_ORDER);
  
  }
}

2.SearchView控件

使用SearchView时,遇到一个问题迟迟没有找到答案:在搜索框中输入字符后点击搜索,这时候搜索框不消失,而且searchView仍处于展开状态,很影响用户体验。如何达到当点击搜索后,searchView就立即折叠?表示该次搜索已经完成。

SearchView.OnQueryTextListener mQueryTextListener = new 
        SearchView.OnQueryTextListener() {
    public boolean onQueryTextSubmit(String query) {
        
        /*非常重要,他表示折叠actionView;mSearchMenu是在onCreateOptionsMenu()中通过menu.findItem(R.id.menu_search)获得;如果要展开actionView,则调用expandActionView()。
        */
        mSearchMenu.collapseActionView();
            new SearchFileThread(query.trim()).start();
            //mSearchView.setFocusable(false);
            //mSearchView.clearFocus();//表示让searchView失去焦点
            return true;
        }

        public boolean onQueryTextChange(String newText) {
            return false;
        }
    };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值