Tro*_*jan 5 android android-widget android-layout
我正在构建一个应用程序,当用户按下应用程序上的"浏览"按钮时,我想显示来自手机的文件夹,用户将选择文件/图像.选择附件后,应用程序将在附件中显示文件名.我正在寻找的是文件附件机制如何在android中工作所以任何代码示例或片段非常感谢.
提前致谢.
你真正想要做的是执行Intent.ACTION_GET_CONTENT.如果指定类型,"file/*"那么文件选择器将允许您从文件系统中选择任何类型的文件.
这里有几个读物:
这是从博客中提取的来源(由Android-er提供):
public class AndroidPick_a_File extends Activity {
TextView textFile;
private static final int PICKFILE_RESULT_CODE = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonPick = (Button)findViewById(R.id.buttonpick);
textFile = (TextView)findViewById(R.id.textfile);
buttonPick.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode){
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK){
String FilePath = data.getData().getPath();
textFile.setText(FilePath);
}
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
获取所选文件的路径后,由您决定如何处理它:在数据库中存储路径,在屏幕上显示等等.
如果要使用默认应用程序打开文件,请按照此博客中的建议操作.再一次,我提取了代码(由Hello World Codes提供):
第一种方式:
String path="File Path";
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);
intent.setData(Uri.fromFile(file));
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)
第二种方式:
String path="File Path";
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=file.getName().substring(file.getName().indexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(file),type);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)
请记得留下感谢应得的人( - .