source: dispositivos_moviles/com.lamerman.FileDialog/src/com/lamerman/FileDialog.java @ fd4a5b9

Last change on this file since fd4a5b9 was 7f76117, checked in by Antonio Araujo Brett <aaraujo@…>, 11 years ago

Agregados los archivos de la librería Android File Dialog a utilizar en el proyecto. mayor información en https://code.google.com/p/android-file-dialog/

  • Property mode set to 100644
File size: 10.1 KB
Line 
1package com.lamerman;
2
3import java.io.File;
4import java.util.ArrayList;
5import java.util.HashMap;
6import java.util.List;
7import java.util.TreeMap;
8
9import android.app.AlertDialog;
10import android.app.ListActivity;
11import android.content.DialogInterface;
12import android.os.Bundle;
13import android.view.KeyEvent;
14import android.view.View;
15import android.view.View.OnClickListener;
16import android.view.inputmethod.InputMethodManager;
17import android.widget.Button;
18import android.widget.EditText;
19import android.widget.LinearLayout;
20import android.widget.ListView;
21import android.widget.SimpleAdapter;
22import android.widget.TextView;
23
24/**
25 * Activity para escolha de arquivos/diretorios.
26 *
27 * @author android
28 *
29 */
30public class FileDialog extends ListActivity {
31
32        /**
33         * Chave de um item da lista de paths.
34         */
35        private static final String ITEM_KEY = "key";
36
37        /**
38         * Imagem de um item da lista de paths (diretorio ou arquivo).
39         */
40        private static final String ITEM_IMAGE = "image";
41
42        /**
43         * Diretorio raiz.
44         */
45        private static final String ROOT = "/";
46
47        /**
48         * Parametro de entrada da Activity: path inicial. Padrao: ROOT.
49         */
50        public static final String START_PATH = "START_PATH";
51
52        /**
53         * Parametro de entrada da Activity: filtro de formatos de arquivos. Padrao:
54         * null.
55         */
56        public static final String FORMAT_FILTER = "FORMAT_FILTER";
57
58        /**
59         * Parametro de saida da Activity: path escolhido. Padrao: null.
60         */
61        public static final String RESULT_PATH = "RESULT_PATH";
62
63        /**
64         * Parametro de entrada da Activity: tipo de selecao: pode criar novos paths
65         * ou nao. Padrao: nao permite.
66         *
67         * @see {@link SelectionMode}
68         */
69        public static final String SELECTION_MODE = "SELECTION_MODE";
70
71        /**
72         * Parametro de entrada da Activity: se e permitido escolher diretorios.
73         * Padrao: falso.
74         */
75        public static final String CAN_SELECT_DIR = "CAN_SELECT_DIR";
76
77        private List<String> path = null;
78        private TextView myPath;
79        private EditText mFileName;
80        private ArrayList<HashMap<String, Object>> mList;
81
82        private Button selectButton;
83
84        private LinearLayout layoutSelect;
85        private LinearLayout layoutCreate;
86        private InputMethodManager inputManager;
87        private String parentPath;
88        private String currentPath = ROOT;
89
90        private int selectionMode = SelectionMode.MODE_CREATE;
91
92        private String[] formatFilter = null;
93
94        private boolean canSelectDir = false;
95
96        private File selectedFile;
97        private HashMap<String, Integer> lastPositions = new HashMap<String, Integer>();
98
99        /**
100         * Called when the activity is first created. Configura todos os parametros
101         * de entrada e das VIEWS..
102         */
103        @Override
104        public void onCreate(Bundle savedInstanceState) {
105                super.onCreate(savedInstanceState);
106                setResult(RESULT_CANCELED, getIntent());
107
108                setContentView(R.layout.file_dialog_main);
109                myPath = (TextView) findViewById(R.id.path);
110                mFileName = (EditText) findViewById(R.id.fdEditTextFile);
111
112                inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
113
114                selectButton = (Button) findViewById(R.id.fdButtonSelect);
115                selectButton.setEnabled(false);
116                selectButton.setOnClickListener(new OnClickListener() {
117
118                        @Override
119                        public void onClick(View v) {
120                                if (selectedFile != null) {
121                                        getIntent().putExtra(RESULT_PATH, selectedFile.getPath());
122                                        setResult(RESULT_OK, getIntent());
123                                        finish();
124                                }
125                        }
126                });
127
128                final Button newButton = (Button) findViewById(R.id.fdButtonNew);
129                newButton.setOnClickListener(new OnClickListener() {
130
131                        @Override
132                        public void onClick(View v) {
133                                setCreateVisible(v);
134
135                                mFileName.setText("");
136                                mFileName.requestFocus();
137                        }
138                });
139
140                selectionMode = getIntent().getIntExtra(SELECTION_MODE, SelectionMode.MODE_CREATE);
141
142                formatFilter = getIntent().getStringArrayExtra(FORMAT_FILTER);
143
144                canSelectDir = getIntent().getBooleanExtra(CAN_SELECT_DIR, false);
145
146                if (selectionMode == SelectionMode.MODE_OPEN) {
147                        newButton.setEnabled(false);
148                }
149
150                layoutSelect = (LinearLayout) findViewById(R.id.fdLinearLayoutSelect);
151                layoutCreate = (LinearLayout) findViewById(R.id.fdLinearLayoutCreate);
152                layoutCreate.setVisibility(View.GONE);
153
154                final Button cancelButton = (Button) findViewById(R.id.fdButtonCancel);
155                cancelButton.setOnClickListener(new OnClickListener() {
156
157                        @Override
158                        public void onClick(View v) {
159                                setSelectVisible(v);
160                        }
161
162                });
163                final Button createButton = (Button) findViewById(R.id.fdButtonCreate);
164                createButton.setOnClickListener(new OnClickListener() {
165
166                        @Override
167                        public void onClick(View v) {
168                                if (mFileName.getText().length() > 0) {
169                                        getIntent().putExtra(RESULT_PATH, currentPath + "/" + mFileName.getText());
170                                        setResult(RESULT_OK, getIntent());
171                                        finish();
172                                }
173                        }
174                });
175
176                String startPath = getIntent().getStringExtra(START_PATH);
177                startPath = startPath != null ? startPath : ROOT;
178                if (canSelectDir) {
179                        File file = new File(startPath);
180                        selectedFile = file;
181                        selectButton.setEnabled(true);
182                }
183                getDir(startPath);
184        }
185
186        private void getDir(String dirPath) {
187
188                boolean useAutoSelection = dirPath.length() < currentPath.length();
189
190                Integer position = lastPositions.get(parentPath);
191
192                getDirImpl(dirPath);
193
194                if (position != null && useAutoSelection) {
195                        getListView().setSelection(position);
196                }
197
198        }
199
200        /**
201         * Monta a estrutura de arquivos e diretorios filhos do diretorio fornecido.
202         *
203         * @param dirPath
204         *            Diretorio pai.
205         */
206        private void getDirImpl(final String dirPath) {
207
208                currentPath = dirPath;
209
210                final List<String> item = new ArrayList<String>();
211                path = new ArrayList<String>();
212                mList = new ArrayList<HashMap<String, Object>>();
213
214                File f = new File(currentPath);
215                File[] files = f.listFiles();
216                if (files == null) {
217                        currentPath = ROOT;
218                        f = new File(currentPath);
219                        files = f.listFiles();
220                }
221                myPath.setText(getText(R.string.location) + ": " + currentPath);
222
223                if (!currentPath.equals(ROOT)) {
224
225                        item.add(ROOT);
226                        addItem(ROOT, R.drawable.folder);
227                        path.add(ROOT);
228
229                        item.add("../");
230                        addItem("../", R.drawable.folder);
231                        path.add(f.getParent());
232                        parentPath = f.getParent();
233
234                }
235
236                TreeMap<String, String> dirsMap = new TreeMap<String, String>();
237                TreeMap<String, String> dirsPathMap = new TreeMap<String, String>();
238                TreeMap<String, String> filesMap = new TreeMap<String, String>();
239                TreeMap<String, String> filesPathMap = new TreeMap<String, String>();
240                for (File file : files) {
241                        if (file.isDirectory()) {
242                                String dirName = file.getName();
243                                dirsMap.put(dirName, dirName);
244                                dirsPathMap.put(dirName, file.getPath());
245                        } else {
246                                final String fileName = file.getName();
247                                final String fileNameLwr = fileName.toLowerCase();
248                                // se ha um filtro de formatos, utiliza-o
249                                if (formatFilter != null) {
250                                        boolean contains = false;
251                                        for (int i = 0; i < formatFilter.length; i++) {
252                                                final String formatLwr = formatFilter[i].toLowerCase();
253                                                if (fileNameLwr.endsWith(formatLwr)) {
254                                                        contains = true;
255                                                        break;
256                                                }
257                                        }
258                                        if (contains) {
259                                                filesMap.put(fileName, fileName);
260                                                filesPathMap.put(fileName, file.getPath());
261                                        }
262                                        // senao, adiciona todos os arquivos
263                                } else {
264                                        filesMap.put(fileName, fileName);
265                                        filesPathMap.put(fileName, file.getPath());
266                                }
267                        }
268                }
269                item.addAll(dirsMap.tailMap("").values());
270                item.addAll(filesMap.tailMap("").values());
271                path.addAll(dirsPathMap.tailMap("").values());
272                path.addAll(filesPathMap.tailMap("").values());
273
274                SimpleAdapter fileList = new SimpleAdapter(this, mList, R.layout.file_dialog_row, new String[] {
275                                ITEM_KEY, ITEM_IMAGE }, new int[] { R.id.fdrowtext, R.id.fdrowimage });
276
277                for (String dir : dirsMap.tailMap("").values()) {
278                        addItem(dir, R.drawable.folder);
279                }
280
281                for (String file : filesMap.tailMap("").values()) {
282                        addItem(file, R.drawable.file);
283                }
284
285                fileList.notifyDataSetChanged();
286
287                setListAdapter(fileList);
288
289        }
290
291        private void addItem(String fileName, int imageId) {
292                HashMap<String, Object> item = new HashMap<String, Object>();
293                item.put(ITEM_KEY, fileName);
294                item.put(ITEM_IMAGE, imageId);
295                mList.add(item);
296        }
297
298        /**
299         * Quando clica no item da lista, deve-se: 1) Se for diretorio, abre seus
300         * arquivos filhos; 2) Se puder escolher diretorio, define-o como sendo o
301         * path escolhido. 3) Se for arquivo, define-o como path escolhido. 4) Ativa
302         * botao de selecao.
303         */
304        @Override
305        protected void onListItemClick(ListView l, View v, int position, long id) {
306
307                File file = new File(path.get(position));
308
309                setSelectVisible(v);
310
311                if (file.isDirectory()) {
312                        selectButton.setEnabled(false);
313                        if (file.canRead()) {
314                                lastPositions.put(currentPath, position);
315                                getDir(path.get(position));
316                                if (canSelectDir) {
317                                        selectedFile = file;
318                                        v.setSelected(true);
319                                        selectButton.setEnabled(true);
320                                }
321                        } else {
322                                new AlertDialog.Builder(this).setIcon(R.drawable.icon)
323                                                .setTitle("[" + file.getName() + "] " + getText(R.string.cant_read_folder))
324                                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
325
326                                                        @Override
327                                                        public void onClick(DialogInterface dialog, int which) {
328
329                                                        }
330                                                }).show();
331                        }
332                } else {
333                        selectedFile = file;
334                        v.setSelected(true);
335                        selectButton.setEnabled(true);
336                }
337        }
338
339        @Override
340        public boolean onKeyDown(int keyCode, KeyEvent event) {
341                if ((keyCode == KeyEvent.KEYCODE_BACK)) {
342                        selectButton.setEnabled(false);
343
344                        if (layoutCreate.getVisibility() == View.VISIBLE) {
345                                layoutCreate.setVisibility(View.GONE);
346                                layoutSelect.setVisibility(View.VISIBLE);
347                        } else {
348                                if (!currentPath.equals(ROOT)) {
349                                        getDir(parentPath);
350                                } else {
351                                        return super.onKeyDown(keyCode, event);
352                                }
353                        }
354
355                        return true;
356                } else {
357                        return super.onKeyDown(keyCode, event);
358                }
359        }
360
361        /**
362         * Define se o botao de CREATE e visivel.
363         *
364         * @param v
365         */
366        private void setCreateVisible(View v) {
367                layoutCreate.setVisibility(View.VISIBLE);
368                layoutSelect.setVisibility(View.GONE);
369
370                inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
371                selectButton.setEnabled(false);
372        }
373
374        /**
375         * Define se o botao de SELECT e visivel.
376         *
377         * @param v
378         */
379        private void setSelectVisible(View v) {
380                layoutCreate.setVisibility(View.GONE);
381                layoutSelect.setVisibility(View.VISIBLE);
382
383                inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
384                selectButton.setEnabled(false);
385        }
386}
Note: See TracBrowser for help on using the repository browser.