现在的位置: 首页 > 综合 > 正文

android学习笔记(5)-一个搜索文件的APP(2)-搜索功能的实现

2013年10月18日 ⁄ 综合 ⁄ 共 4055字 ⁄ 字号 评论关闭

接上一篇,今天把搜索的代码放上去了。效果图如下。



MainActivity.java

package com.stk.afinder;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.view.View;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.widget.EditText;
import java.util.ArrayList;
import java.io.File;

public class MainActivity extends Activity {

    static private ArrayList<String> search_result = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView list = (ListView) findViewById(R.id.result_list);
        list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,search_result));

        Button searchBn = (Button) findViewById(R.id.search_bn);
        searchBn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (search_result != null) {
                    search_result.clear();
                }

                EditText et = (EditText) findViewById(R.id.file_name_edit);
                MainActivity.this.searchFile(et.getText().toString().trim(), "/sdcard");
                ((ArrayAdapter)((ListView)MainActivity.this.findViewById(R.id.result_list)).getAdapter()).notifyDataSetChanged();
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void searchFile(String filename, String path) {
        File[] files = null;
        try {
            files = new File(path).listFiles();
        } catch (Exception e) {
            files = null;
            Toast.makeText(this, getString(R.string.open_file_err), Toast.LENGTH_SHORT).show();
            return;
        }

        for (File file : files) {
            if (file.isDirectory() && file.listFiles() != null) {
                searchFile(filename, file.getPath());
            } else if (file.isFile()) {                
                if (filename == null || filename.isEmpty()) {
                    search_result.add(file.getPath());
                } else {
                    String name = file.getName();
                    if (name.indexOf(filename) != -1) {
                        search_result.add(file.getPath());
                    }
                }
            }
        }
    }
}

其中实现搜索的代码是 private void searchFile(String filename, String path) 这个函数。

为了简单起见目前设置搜索的路径代码中硬编码为 “/sdcard”,预先在手机 /sdcard/download/ 目录下创建了几个文件。

小技巧:通过android sdk自带的工具adb操作虚拟机中的文件。

在命令行中进入android sdk安装目录中的 platform-tools 目录。

使用命令 ./adb shell 连接到 shell。android手机操作系统底层是基于Linux的,所以进入shell后基本的linux命令都可以用。

比如 ls 查看文件,cd 切换目录,touch 创建文件。完成后查看结果如下:

# cd Download
# ls
a.txt
ac.txt
b.txt
c.txt

与之前的MainActivity类代码相比,除了增加了一个private void searchFile(String filename, String path) 函数外,onCreate函数中也增加了部分内容。

1、增加了显示结果的ListView组件的处理。

        ListView list = (ListView) findViewById(R.id.result_list); //获取组件
        list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,search_result)); //绑定适配器

我们的查找结果是一个列表,包含了所有匹配条件的文件的完整路径,我们使用一个字符串数组列表保存结果。

static private ArrayList<String> search_result = new ArrayList<String>();

要使ListView与数据绑定,显示数据并且当数据发生改变时能够刷新,必须给ListView绑定一个适配器。

我们这里使用了最简单的ArrayAdapter,系统自带的一个适配器。这是最简单的一个适配器。


2、增加了搜索按钮的点击事件处理。

Button searchBn = (Button) findViewById(R.id.search_bn);
        searchBn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (search_result != null) {
                    search_result.clear(); //清除上次的结果
                }

                EditText et = (EditText) findViewById(R.id.file_name_edit); // 获取文件名的组件
                MainActivity.this.searchFile(et.getText().toString().trim(), "/sdcard"); //调用搜索函数
                ((ArrayAdapter)((ListView)MainActivity.this.findViewById(R.id.result_list)).getAdapter()).notifyDataSetChanged(); // 搜索完成后调用适配器的 notifyDataChanged 函数通知适配器数据源发生了改变。
            }
        });

3、提示

searchFile函数中有如下处理

try {
            files = new File(path).listFiles();
        } catch (Exception e) {
            files = null;
            Toast.makeText(this, getString(R.string.open_file_err), Toast.LENGTH_SHORT).show();
            return;
        }

open_file_err 是我们在String.xml资源文件中新增的一个错误提示字符串

<string name="open_file_err">打开搜索目录失败,请检查设置是否正确。</string>

Toast类的makeText函数声明如下:

    /**
     * Make a standard toast that just contains a text view.
     *
     * @param context  The context to use.  Usually your {@link android.app.Application}
     *                 or {@link android.app.Activity} object.
     * @param text     The text to show.  Can be formatted text.
     * @param duration How long to display the message.  Either {@link #LENGTH_SHORT} or
     *                 {@link #LENGTH_LONG}
     *
     */
    public static Toast makeText(Context context, CharSequence text, int duration)

如果用户没有输入任何字符串而直接点击按钮,将会列出 /sdcard 目录下的所有文件。



写东西好麻烦啊 :( ,比写代码麻烦多了。

总是写的简单了,好多东西没有写出来。

抱歉!评论已关闭.