实现点击Button选择文件, 在TextView上显示Uri
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context="com.example.filetest.MainActivity" > 10 11 <TextView 12 android:id="@+id/textView_uri" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:text="@string/hello_world" /> 16 <Button 17 android:id="@+id/btn_find" 18 android:layout_width="match_parent" 19 android:layout_height="wrap_content" 20 android:layout_below="@+id/textView_uri" 21 android:text="find"/> 22 23 </RelativeLayout>
1 package com.example.filetest; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.net.Uri; 6 import android.os.Bundle; 7 import android.view.Menu; 8 import android.view.MenuItem; 9 import android.view.View; 10 import android.view.View.OnClickListener; 11 import android.widget.Button; 12 import android.widget.TextView; 13 14 15 public class MainActivity extends Activity { 16 17 protected static final int FILE_SELECT_CODE = 0; 18 private Button button; 19 private TextView textView; 20 21 @Override 22 protected void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 setContentView(R.layout.activity_main); 25 26 button = (Button)findViewById(R.id.btn_find); 27 textView = (TextView)findViewById(R.id.textView_uri); 28 29 button.setOnClickListener(new OnClickListener() { 30 @Override 31 public void onClick(View v) { 32 // TODO Auto-generated method stub 33 Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 34 intent.setType("*/*"); // 选择文件类型 35 intent.addCategory(Intent.CATEGORY_OPENABLE); 36 startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE); 37 } 38 }); 39 } 40 41 @Override 42 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 43 // TODO Auto-generated method stub 44 switch(requestCode){ 45 case FILE_SELECT_CODE: 46 if(resultCode == RESULT_OK){ 47 Uri uri = data.getData(); 48 String path = uri.getPath(); 49 textView.setText(path); 50 } 51 break; 52 } 53 super.onActivityResult(requestCode, resultCode, data); 54 } 55 }
截图
选择文件之后