In activityaction, there is a "action_get_content" String constant, which allows users to select a specific type of data and return the URI of the data. we can use this constant and set the type to "image/*" to obtain all images in the Android mobile phone.
Main. xml:
- <? XML version = "1.0" encoding = "UTF-8"?>
- <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
- Android: Orientation = "vertical"
- Android: layout_width = "fill_parent"
- Android: layout_height = "fill_parent"
- >
- <Textview
- Android: layout_width = "fill_parent"
- Android: layout_height = "wrap_content"
- Android: text = "@ string/hello"
- />
- <Button
- Android: Id = "@ + ID/B01"
- Android: layout_width = "fill_parent"
- Android: layout_height = "wrap_content"
- />
- <Imageview
- Android: Id = "@ + ID/iv01"
- Android: layout_width = "fill_parent"
- Android: layout_height = "wrap_content"
- />
- </Linearlayout>
Lesson_01_pic.java:
- Package com. yfz;
- Import java. Io. filenotfoundexception;
- Import Android. App. activity;
- Import Android. content. contentresolver;
- Import Android. content. intent;
- Import Android. Graphics. Bitmap;
- Import Android. Graphics. bitmapfactory;
- Import android.net. Uri;
- Import Android. OS. Bundle;
- Import Android. util. log;
- Import Android. View. view;
- Import Android. widget. Button;
- Import Android. widget. imageview;
- Public class lesson_01_pic extends activity {
- /** Called when the activity is first created .*/
- @ Override
- Public void oncreate (bundle savedinstancestate ){
- Super. oncreate (savedinstancestate );
- Setcontentview (R. layout. Main );
- Button button = (button) findviewbyid (R. Id. B01 );
- Button. settext ("select image ");
- Button. setonclicklistener (New button. onclicklistener (){
- @ Override
- Public void onclick (view v ){
- Intent intent = new intent ();
- /* Enable pictures image type to set to image */
- Intent. settype ("image /*");
- /* Use the intent. action_get_content action */
- Intent. setaction (intent. action_get_content );
- /* Return to the current screen after obtaining the photo */
- Startactivityforresult (intent, 1 );
- }
- });
- }
- @ Override
- Protected void onactivityresult (INT requestcode, int resultcode, intent data ){
- If (resultcode = result_ OK ){
- Uri uri = data. getdata ();
- Log. E ("Uri", Uri. tostring ());
- Contentresolver Cr = This. getcontentresolver ();
- Try {
- Bitmap bitmap = bitmapfactory. decodestream (Cr. openinputstream (URI ));
- Imageview = (imageview) findviewbyid (R. Id. iv01 );
- /* Set bitmap to imageview */
- Imageview. setimagebitmap (Bitmap );
- } Catch (filenotfoundexception e ){
- Log. E ("exception", E. getmessage (), e );
- }
- }
- Super. onactivityresult (requestcode, resultcode, data );
- }
- }