试试下面的例子:
Demo13.class:---------
public class Demo13 extends AppCompatActivity {
private Button b;
private EditText edt;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo15);
edt = (EditText) findViewById(R.id.edt);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!edt.getText().toString().isEmpty()) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), edt.getText().toString());
if(mediaStorageDir.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(mediaStorageDir), "resource/folder");
Intent chooser = Intent.createChooser(intent, "File");
if (intent.resolveActivity(getApplicationContext().getPackageManager()) != null) {
startActivity(chooser);
} else {
createInfoDialog(Demo13.this, "Info", "Found no app that can handle this request. " +
"Please install a file browser/manager like ES File Explorer or browse the file yourself by following the path after finished Syn in the log above", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//nothing
}
}).show();
// if you reach this place, it means there is no file
// explorer app installed on your device that can handle this request.
}
}else{
createInfoDialog(Demo13.this, "Info", "Sub-Folder not found", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// nothing
}
}).show();
}
}else{
createInfoDialog(Demo13.this, "Info", "Please insert a valid sub-folder name", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// nothing
}
}).show();
}
}
});
}
public AlertDialog createInfoDialog(Context finalContext, String title, String message,
DialogInterface.OnClickListener onOkListener) {
AlertDialog a = new AlertDialog.Builder(finalContext).setTitle(
title)
.setMessage(message)
.setNeutralButton("OK", onOkListener).create();
return a;
}
}
demo13.xml:------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a valid sub-folder"
android:id="@+id/edt"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:layout_marginTop="50dp"
android:text="Open"
android:id="@+id/b"/>
</LinearLayout>