这是Intent的一个用法。
在ActivityAction里面有一个“ACTION_GET_CONTENT”字符串常量,该常量让用户选择特定类型的数据。
intent.setType("image/*"); 选择本地所有的图片。
返回该数据的URI.我们利用该常量生成该图片的位图Bitmap,然后为添加到图片控件(ImageView)上就行了。
选择你想要的图片:
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"
- >
- <Button
- android:id="@+id/button"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <ImageView
- android:id="@+id/image"
- android:layout_width="fill_parent"
- android:scaleType="fitXY"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
- package xiaosi.image;
- 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.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ImageView;
- public class ImageActivity extends Activity {
- /** Called when the activity is first created. */
- private Button button = null;
- private ImageView imageView = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- button = (Button)findViewById(R.id.button);
- button.setText("选择图片");
- button.setOnClickListener(new ButtonListener());
- }
- private class ButtonListener implements OnClickListener{
- public void onClick(View v)
- {
- Intent intent = new Intent();
- /* 开启Pictures画面Type设定为image */
- intent.setType("image/*");
- /* 使用Intent.ACTION_GET_CONTENT这个Action */
- intent.setAction(Intent.ACTION_GET_CONTENT);
- /* 取得相片后返回本画面 */
- 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 contentResolver = this.getContentResolver();
- try {
- Bitmap bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri));
- imageView = (ImageView) findViewById(R.id.image);
- /* 将Bitmap设定到ImageView */
- imageView.setImageBitmap(bitmap);
- }
- catch (FileNotFoundException e){
- Log.e("Exception", e.getMessage(),e);
- }
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
- }
源代码:点击打开链接