最常用的方法是使用onCreateDialog()方法创建对话框,这个网上写的很多,不多介绍,但是对于我这样的新手来说,连如何调用onCreateDialog()方法都不知道,那就应该深究深究了,花了半天时间看了很多博文,终于在一知半解下解决了打开目录,选择文件的问题。简单记录下来,便于以后使用:
一:首先要弄明白showDialog()、onPrepareDialog()和onCreateDialog()的关系:showDialog()调用createDialog()和onPrepareDialog(),其中createDialog()调用onCreateDialog()
二:
使用的是Button时
1
2
3
4
5
6
7 |
// 设置单击按钮时打开文件对话框 findViewById(R.id.button_openfile).setOnClickListener( new
OnClickListener() { @Override public
void onClick(View arg0) { showDialog( int
id); } }); |
使用的是Preference时
1
2
3
4
5
6
7 |
preference.setOnPreferenceClickListener( new
OnPreferenceClickListener(){ @Override public
boolean onPreferenceClick(Preference preference) { showDialog( int
id); return
true ; } }); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 |
@Override protected
Dialog onCreateDialog( int
id) { Map<String, Integer> images = new
HashMap<String, Integer>(); // 下面几句设置各文件类型的图标, 需要你先把图标添加到资源文件夹 images.put(OpenFileDialog.sRoot, R.drawable.filedialog_root); // 根目录图标 images.put(OpenFileDialog.sParent, R.drawable.filedialog_folder_up); //返回上一层的图标 images.put(OpenFileDialog.sFolder, R.drawable.filedialog_folder); //文件夹图标 images.put( "xls" , R.drawable.excel); //excel文件图标 images.put(OpenFileDialog.sEmpty, R.drawable.filedialog_root); Dialog dialog = OpenFileDialog.createDialog(id, this , "打开文件" , new
CallbackBundle() { @Override public
void callback(Bundle bundle) { String filepath = bundle.getString( "path" ); setTitle(filepath); // 把文件路径显示在标题上 } }, ".xls;" , images); return
dialog; } |
四
1 |
因为不同按钮的showDialog()都可以触发onCreateDialog()方法,因此需要加个识别条件 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 |
static
private int openfileDialogId = 0 ; @Override protected
Dialog onCreateDialog( int
id) { if (openfileDialogId == id){ Map<String, Integer> images = new
HashMap<String, Integer>(); // 下面几句设置各文件类型的图标, 需要你先把图标添加到资源文件夹 images.put(OpenFileDialog.sRoot, R.drawable.filedialog_root); // 根目录图标 images.put(OpenFileDialog.sParent, R.drawable.filedialog_folder_up); //返回上一层的图标 images.put(OpenFileDialog.sFolder, R.drawable.filedialog_folder); //文件夹图标 images.put( "xls" , R.drawable.excel); //excel文件图标 images.put(OpenFileDialog.sEmpty, R.drawable.filedialog_root); Dialog dialog = OpenFileDialog.createDialog(id, this , "打开文件" , new
CallbackBundle() { @Override public
void callback(Bundle bundle) { String filepath = bundle.getString( "path" ); setTitle(filepath); // 把文件路径显示在标题上 } }, ".xls;" , images); return
dialog; } return
null ; } |
原文:http://www.cnblogs.com/chenyouc/p/3594816.html