Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android初學之第一個Android程序:文件浏覽器

Android初學之第一個Android程序:文件浏覽器

編輯:關於Android編程

文件浏覽器筆記

文件浏覽器用來讀取android系統中的所有文件和文件夾。具體說明如下:

最上面顯示當前的文件路徑。如果是根目錄,則顯示“/”; 第二行是返回上一級按鈕。如果當前處於根目錄下,則該行不顯示; 若當前是文件夾,則可點擊,進入下一級目錄,若是文件,點擊的話會提示不支持讀取。

新加功能,監聽外部存儲設備USB和SD卡插拔廣播。代碼如下:

public class UsbBroadCastReceiver extends BroadcastReceiver {

    @SuppressLint("ShowToast")
    @Override
    public void onReceive(final Context context, final Intent intent) {
        final String action = intent.getAction();
        final IntentFilter iFilter = new IntentFilter();
        iFilter.addDataScheme("file");

        if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
            Toast.makeText(context, "外部存儲設備已移除", 1000).show();
        } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
            Toast.makeText(context, "正在准備外部USB存儲設備", 1000).show();
        } else if (action.equals(Intent.ACTION_MEDIA_CHECKING)) {
            Toast.makeText(context, "正在准備外部SD卡存儲設備", 1000).show();
        }

    }

當然還要在AndroidMainfest.xml中添加相應配置:

    
            
                
                
                

                
            
     

下面是主要的程序源碼:

FileManager.java

package browers;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.example.browers.R;

public class FileManager extends Activity {
    private TextView mCurrentPath;
    private TextView mReturn;
    private ListView mList;
    private View mPathLine;
    private String mReturnPath = null;
    private FileManagerAdapter adapter;
    private ArrayList> infos = null;

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

    private void initView() {
        mCurrentPath = (TextView) findViewById(R.id.file_path);
        mPathLine = findViewById(R.id.file_path_line);
        mReturn = (TextView) findViewById(R.id.file_return);
        mList = (ListView) findViewById(R.id.file_list);

      //為listview添加一個響應事件
        mList.setOnItemClickListener(clickListener);
      //處理用戶短時間單擊按鈕的事件
        mReturn.setOnClickListener(new OnClickListener() {

          //如果出現返回上一級字符和mreturnpath長度不等於0,則初始化返回的那個路徑
            @Override
            public void onClick(View v) {
                String returnStr = mReturn.getText().toString();
                if (mReturnPath.length() > 0 && returnStr.equals("返回上一級")) {
                    initList(mReturnPath);
                }

            }
        });

        initList("/"); // 初始化從根目錄開始
    }

    private void initList(String path) {
        File file = new File(path);
        File[] fileList = file.listFiles();
        infos = new ArrayList>();
        Map item = new HashMap();
        Drawable drawable;
        if (path.equals("/")) { // 如果當前為根目錄,返回上一級按鈕,不顯示
            drawable = getResources().getDrawable(R.drawable.root_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                    drawable.getMinimumHeight());
            mCurrentPath.setCompoundDrawablePadding(10);
            mCurrentPath.setCompoundDrawables(drawable, null, null, null);
            mCurrentPath.setText("根目錄列表");
            mReturn.setVisibility(View.GONE);
            mPathLine.setVisibility(View.GONE);
        } else {
            drawable = getResources().getDrawable(R.drawable.root_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                    drawable.getMinimumHeight());
            mReturn.setCompoundDrawables(drawable, null, null, null);
            mReturn.setText("返回上一級");
            mReturnPath = file.getParent(); // 保存該級目錄的上一級路徑
            mCurrentPath.setVisibility(View.VISIBLE);
            mPathLine.setVisibility(View.VISIBLE);
            mCurrentPath.setText(file.getPath());
        }

        try {
            for (int i = 0; i < fileList.length; i++) {
                item = new HashMap();
                File fileItem = fileList[i];
                if (fileItem.isDirectory()) { // 如果當前文件為文件夾,設置文件夾的圖標
                    item.put("icon", R.drawable.floder_icon);
                } else
                    item.put("icon", R.drawable.child_icon);
                item.put("name", fileItem.getName()); //實例化item對象
                item.put("path", fileItem.getAbsolutePath());
                infos.add(item);//將item對象添加到infos集合中
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        adapter = new FileManagerAdapter(this);
        adapter.setFileListInfo(infos);
        mList.setAdapter(adapter);
    }

    private final OnItemClickListener clickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView arg0, View arg1, int position,
                long arg3) {
            File file = new File((String) (infos.get(position).get("path")));
            if (file.isDirectory()) { // 若點擊文件夾,則進入下一級目錄
                String nextPath = (String) (infos.get(position).get("path"));
                initList(nextPath);
            } else { // 若點擊文件,則將文件名發送至調用文件浏覽器的主界面
                Intent intent = new Intent();
                intent.setClass(FileManager.this, Activity.class);
                intent.putExtra("fileName",
                        (String) (infos.get(position).get("name")));
                intent.putExtra("path",
                        (String) (infos.get(position).get("path")));
                setResult(RESULT_OK, intent);
                finish();
            }

        }
    };
}

相應的adapter文件:

FileManagerAdapter.java

package browers;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.browers.R;

public class FileManagerAdapter extends BaseAdapter {
    private final Context mContext;
    private final List> list = new ArrayList>();

    public FileManagerAdapter(final Context context) {
        super();
        mContext = context;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(final int position) {
        return position;
    }

    @Override
    public long getItemId(final int arg0) {
        return arg0;
    }

    @Override
    public View getView(final int position, View convertView,
            final ViewGroup arg2) {
        FileMangerHolder holder;

        if (null == convertView) {
            holder = new FileMangerHolder();
            convertView = LayoutInflater.from(mContext).inflate(
                    R.layout.file_item, null);
            holder.icon = (ImageView) convertView
                    .findViewById(R.id.file_item_icon);
            holder.name = (TextView) convertView
                    .findViewById(R.id.file_item_name);
            convertView.setTag(holder);
        } else {
            holder = (FileMangerHolder) convertView.getTag();
        }

        holder.icon
                .setImageResource((Integer) (list.get(position).get("icon")));
        holder.name.setText((String) (list.get(position).get("name")));

        return convertView;
    }

    public class FileMangerHolder {
        public ImageView icon;
        public TextView name;
    }

    // The information add to listView
    public void setFileListInfo(final List> infos) {
        list.addAll(infos);
        notifyDataSetChanged();
    }
}

最後是兩個布局文件:file_list.xml和file_item.xml

file_list.xml




    

    

    

    

    

file_item.xml




    

        

        
    

以上是全部源碼,換了環境運得時,包名可能需要根據自己的目錄路徑做一下相應的更改,其他的基本沒有問題,程序很簡單,也可以很好的進行拓展。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved