Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 入門實作:打造一個文件夾管理器(一)主體架構與列表呈現

編輯:關於 Android 程式設計

我們手上的裝置通常都自帶廠商開發的檔案管理、相機等系統應用。今天要動手做的,是一個入門級的文件夾管理器。

整個專案大約六個類別,不摻雜任何外部服務,就是一個純粹的本地檔案瀏覽器。

功能設計:檔案複製、文件夾複製、批次複製、刪除檔案、刪除文件夾、批次刪除、檔案分類瀏覽。(檔案搜尋先留白,有興趣可以自己補上。)

技術點:DrawerLayout、ListView、Fragment、IO 串流、序列化、檔案過濾、檔案排序、ActionBar、Adapter、v4 套件與相關事件處理。

第一步:申請讀寫權限

在清單檔中加入外部儲存空間的讀寫權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

若 targetSdkVersion 為 23 以上,光是宣告在清單檔還不夠——必須在執行期動態向使用者請求 READ_EXTERNAL_STORAGE 權限,否則 getExternalStorageDirectory().listFiles() 會回傳 null。這是新手最常卡住的地方。

主界面:DrawerLayout + 多個 Fragment

整體架構是左側抽屜做分類導覽(檔案總覽、音樂、影片、圖片),右側內容區用四個 Fragment 輪替:

public class MainActivity extends Activity implements OnItemClickListener {

    private ActionBar actionbar;
    private ActionBarDrawerToggle drawertoggle;
    private DrawerLayout drawerLayout;
    private String[] drawerdata;
    private int[] list_image = { R.drawable.cunchu, R.drawable.music,
                                 R.drawable.movies, R.drawable.photos };
    private static int index = -1;
    private static File currentpath;
    private static File SDpath;
    private static Context mContext;

    private FragmentA fragmentA;   // 檔案總覽
    private FragmentB fragmentB;   // 音樂
    private FragmentC fragmentC;   // 影片
    private FragmentD fragmentD;   // 圖片

    private static boolean copy;
    private static MenuItem paste;
    private static FileOpreationUitl opreaFile = new FileOpreationUitl();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;

        initDrawerLayout();

        fragmentA = new FragmentA();
        fragmentB = new FragmentB();
        fragmentC = new FragmentC();
        fragmentD = new FragmentD();

        getFragmentManager().beginTransaction()
                .add(R.id.drawer_frame_a, fragmentA)
                .commit();
    }
}

抽屜的初始化與連動

private void initDrawerLayout() {
    drawerLayout = (DrawerLayout) findViewById(R.id.chouti);
    actionbar = getActionBar();
    actionbar.setDisplayHomeAsUpEnabled(true);

    drawertoggle = new ActionBarDrawerToggle(this,
            drawerLayout,               // 抽屜容器
            R.drawable.ic_drawer,       // 抽屜圖示
            R.string.drawer_open, R.string.app_name) {

        public void onDrawerOpened(View drawerView) {
            actionbar.setTitle(index != -1 ? drawerdata[index] : R.string.app_name);
            invalidateOptionsMenu();    // 選項選單重繪
            super.onDrawerOpened(drawerView);
        }

        public void onDrawerClosed(View drawerView) {
            actionbar.setTitle(index != -1 ? drawerdata[index] : R.string.app_name);
            invalidateOptionsMenu();
            super.onDrawerClosed(drawerView);
        }
    };

    drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
    drawerLayout.setDrawerListener(drawertoggle);
}

// 替換抽屜開關上的圖示(箭頭與三條槓的切換動畫)
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    drawertoggle.syncState();
}

drawertoggle.syncState() 這行不能省,否則抽屜開關的圖示不會跟著狀態旋轉。

選項選單:抽屜打開時要藏起「新增」

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    paste = menu.findItem(R.id.paste);
    return true;
}

// 選項選單的預處理:抽屜打開時隱藏與當前頁面無關的項目
public boolean onPrepareOptionsMenu(Menu menu) {
    if (drawerLayout.isDrawerOpen(Gravity.START)) {
        menu.findItem(R.id.action_menu_new).setVisible(false);
    }
    return super.onPrepareOptionsMenu(menu);
}

public boolean onOptionsItemSelected(MenuItem item) {
    if (drawertoggle.onOptionsItemSelected(item)) {
        return true;   // 交給抽屜開關處理
    }
    switch (item.getItemId()) {
        case R.id.paste:
            copy = false;
            fragmentA.Paste();   // 隱藏貼上按鈕
            for (int i = 0; i < fragmentA.filelist.size(); i++) {
                opreaFile.copyDirectory(fragmentA.filelist.get(i), currentpath);
            }
            fragmentA.filelist.clear();
            fragmentA.openFile(currentpath);
            fragmentA.showMessage("執行粘貼");
            break;

        case R.id.action_menu_new:
            View view = LayoutInflater.from(this).inflate(R.layout.list_item, null);
            final EditText newFile = (EditText) view.findViewById(R.id.newFile);
            new AlertDialog.Builder(this)
                    .setTitle("新建文件")
                    .setView(view)
                    .setPositiveButton("確定", new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            String path = currentpath.getAbsolutePath()
                                        + "/" + newFile.getText().toString();
                            File f = new File(path);
                            if (!f.exists()) {
                                f.mkdirs();
                            }
                            fragmentA.filelist.clear();
                            fragmentA.openFile(currentpath);
                            fragmentA.showMessage("執行新建");
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
            break;

        case R.id.action_menu_search:
            break;
    }
    return super.onOptionsItemSelected(item);
}

返回鍵:先回上一層,再問要不要離開

這是檔案管理器必備的互動邏輯——按返回鍵不該直接結束程式,而應該先回到上一層目錄:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (currentpath.equals(SDpath)) {
            // 已在根目錄
            if (!exit) {
                fragmentA.showMessage("再按返回則退出程式!");
                exit = true;
            } else {
                finish();
            }
        } else {
            // 回到上一層
            exit = false;
            File path = currentpath.getParentFile();
            fragmentA.openFile(path);
            fragmentA.showpath.setText(String.valueOf(path));
            fragmentA.adapter.notifyDataSetChanged();
        }
        return true;   // 吃掉返回鍵,不讓系統接手
    }
    return super.onKeyDown(keyCode, event);
}

「再按一次退出」是這個模式的核心,用一個 boolean 旗標記錄狀態即可。若再加上 postDelayed() 在兩秒後自動重設旗標,體驗會更好。

FragmentA:檔案總覽與多選操作

public static class FragmentA extends Fragment
        implements MultiChoiceModeListener, OnItemClickListener {

    public static TextView showpath;
    private ListView listview;
    private FragmentAdapter adapter;
    private File[] mfileData;
    private List<File> filelist = new ArrayList<File>();

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_a, container, false);
        showpath = (TextView) view.findViewById(R.id.showpath);
        listview = (ListView) view.findViewById(R.id.listView);
        bindData();
        return view;
    }

    public void bindData() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            SDpath = Environment.getExternalStorageDirectory();
            showpath.setText(String.valueOf(SDpath));
            getFileData();
        } else {
            showMessage("SD 卡出現異常");
        }
    }

    private File[] getFileData() {
        mfileData = SDpath.listFiles(new CustomFileFilter());  // 過濾隱藏檔
        mfileData = FileSort.sortFile(mfileData);              // 排序
        openFile(SDpath);
        return mfileData;
    }

    public void Paste() {
        paste.setVisible(copy);
        paste.setShowAsAction(copy ? MenuItem.SHOW_AS_ACTION_ALWAYS
                                   : MenuItem.SHOW_AS_ACTION_NEVER);
    }

    public void openFile(File path) {
        currentpath = path;
        mfileData = path.listFiles(new CustomFileFilter());
        mfileData = FileSort.sortFile(mfileData);

        adapter = new FragmentAdapter(mfileData, getActivity());
        listview.setAdapter(adapter);

        listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        listview.setMultiChoiceModeListener(FragmentA.this);
        listview.setOnItemClickListener(this);
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        File file = mfileData[position];
        showpath.setText(String.valueOf(file));
        if (file.isDirectory()) {
            openFile(file);        // 資料夾:進入下一層
            adapter.notifyDataSetChanged();
        } else {
            openWithSystemApp(file);   // 檔案:呼叫系統檢視器
        }
    }

    private void openWithSystemApp(File file) {
        Uri uri = Uri.fromFile(file);
        String[] projection = { MediaStore.Files.FileColumns.MIME_TYPE };
        Cursor cursor = getActivity().getContentResolver().query(
                MediaStore.Files.getContentUri("external"),
                projection,
                MediaStore.Files.FileColumns.DATA + "=?",
                new String[]{ file.getAbsolutePath() },
                null);
        String mime = "*/*";
        if (cursor != null && cursor.moveToFirst()) {
            mime = cursor.getString(0);
            cursor.close();
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, mime);
        startActivity(intent);
    }

    public void showMessage(String info) {
        Toast.makeText(mContext, info, 1000).show();
    }
}

批次刪除:MultiChoiceModeListener 的實作要點

public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    SparseBooleanArray array = listview.getCheckedItemPositions();
    switch (item.getItemId()) {
        case R.id.remove:
            // 注意:處理 SparseBooleanArray 時避免使用靜態方法與靜態變數,
            // 靜態不能再次呼叫靜態,否則容易出問題
            for (int i = 0; i < array.size(); i++) {
                if (array.valueAt(i)) {
                    opreaFile.deleteFile(mfileData[array.keyAt(i)]);
                }
            }
            openFile(currentpath);
            showMessage("刪除成功");
            mode.finish();
            break;

        case R.id.copy:
            copy = true;
            Paste();   // 顯示貼上按鈕
            mode.finish();
            break;
    }
    return false;
}

這裡有個細節值得留意:SparseBooleanArray 只記錄「值為 true」的項目,因此迴圈必須用 array.size() 而非 mfileData.length,並以 keyAt(i) 取回真正的索引。若誤用位置 i 當索引,刪除的檔案就會全部錯位。

版面配置

主佈局 activity_main.xml:

<android.support.v4.widget.DrawerLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/chouti"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/drawer_frame_a"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/drawer_list"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#eee" />
</android.support.v4.widget.DrawerLayout>

清單項佈局 file_listview.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/drawer_bg" >

    <ImageView
        android:id="@+id/filelist_imageview"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="10dp"
        android:src="@drawable/photos" />

    <TextView
        android:id="@+id/filelist_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_toRightOf="@+id/filelist_imageview"
        android:gravity="center_vertical"
        android:text="showfiletext" />

    <TextView
        android:id="@+id/filelist_timeText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/filelist_textview"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/filelist_textview"
        android:text="time" />
</RelativeLayout>

自定義 Adapter:型別配圖與 ViewHolder 複用

public class FragmentAdapter extends BaseAdapter {

    private Context mContext;
    private File[] mfileData;
    private LayoutInflater mlayoutinflater;

    public FragmentAdapter(File[] files, Context pContext) {
        mContext = pContext;
        mfileData = files;
        mlayoutinflater = LayoutInflater.from(mContext);
    }

    public void updata(File[] pfile) { mfileData = pfile; }

    public int getCount() { return mfileData == null ? 0 : mfileData.length; }
    public Object getItem(int position) { return mfileData[position]; }
    public long getItemId(int position) { return position; }

    // ViewHolder 模式:避免每格都重新 findViewById,顯著降低 getView 的開銷
    public static class ViewHolder {
        public ImageView mFileImage;
        public TextView mFileName;
        public TextView mFileTime;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = mlayoutinflater.inflate(R.layout.file_listview, null);
            holder.mFileImage = (ImageView) v.findViewById(R.id.filelist_imageview);
            holder.mFileName  = (TextView)  v.findViewById(R.id.filelist_textview);
            holder.mFileTime  = (TextView)  v.findViewById(R.id.filelist_timeText);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

        File file = mfileData[position];
        String name = file.getName();
        String time = new Date(file.lastModified()).toLocaleString();

        if (file.isDirectory() && file.canRead()) {
            holder.mFileImage.setImageResource(R.drawable.wenjianjia);
        } else if (name.endsWith(".txt")) {
            holder.mFileImage.setImageResource(R.drawable.wenjian);
        } else if (name.endsWith(".png") || name.endsWith(".jpg")
                || name.endsWith(".jpeg") || name.endsWith(".gif")) {
            holder.mFileImage.setTag(file.getAbsolutePath());
            holder.mFileImage.setImageResource(R.drawable.ic_action_picture);
        } else if (name.endsWith(".mp4") || name.endsWith(".avi")
                || name.endsWith(".3gp") || name.endsWith(".rmvb")) {
            holder.mFileImage.setImageResource(R.drawable.ic_action_video);
        } else if (name.endsWith("mp3")) {
            holder.mFileImage.setImageResource(R.drawable.mp3);
        } else if (name.endsWith("doc")) {
            holder.mFileImage.setImageResource(R.drawable.word);
        } else {
            holder.mFileImage.setImageResource(R.drawable.wenjian);
        }

        holder.mFileName.setText(name);
        holder.mFileTime.setText(time);
        return v;
    }
}

這裡原範例有兩個可以改進的地方,順手提出來:

第一,時間顯示。原程式碼一律用 new Date(System.currentTimeMillis()),也就是「現在時間」,導致所有檔案的修改時間都一樣。正確做法是用 file.lastModified() 取得檔案真正的時間戳記。

第二,副檔名判斷。用一長串 endsWith() 判斷雖然直白,但擴充性差。實務上建議先取 name.lastIndexOf('.') 抽出副檔名轉小寫,再用 Map 或 switch 對應圖示資源,新增型別時只改一處即可。另外原程式碼漏了 endsWith(".txt") 以外多數型別的 else 分支,導致部分檔案沒有圖示,這裡已補上預設值。

主布局效果圖:

至此主活動與列表呈現就完成了。下一篇接著實作檔案操作類別——複製、刪除、遞迴遍歷與媒體分類。

測試提醒:若使用模擬器,請確認已建立並掛載 SD 卡(模擬器建立時的 SDCard size 選項);若記憶卡是空的,請自行放入一些測試檔案,否則列表會一片空白。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved