//选择图片按钮
private Button button;
//分享按钮
private ImageButton shareButton;
Uri uri;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//得到控件对象
button = (Button)findViewById(R.id.b01);
shareButton = (ImageButton) this.findViewById(R.id.share);
button.setText("选择图片");
//给选择图片按钮添加事件监听
button.setOnClickListener(new Button.OnClickListener(){
@Override
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);
}
});
//给分享按钮添加监听
shareButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//创建Intent
/*Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "分享一个图片");
startActivity(intent.createChooser(intent, "分享"));*/
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_TEXT, "分享一个图片");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(intent.createChooser(intent, "分享"));
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
uri = data.getData();
Log.e("uri", uri.toString());
ContentResolver cr = this.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
ImageView imageView = (ImageView) findViewById(R.id.iv01);
/* 将Bitmap设定到ImageView */
imageView.setImageBitmap(bitmap);
//创建IntentIntent intent = new Intent(Intent.ACTION_SEND,Uri.parse(""));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
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="hello"
/>
<Button
android:id="@+id/b01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press Me"
/>
<ImageView
android:id="@+id/iv01"
android:layout_width="200dip"
android:layout_height="200dip"
/>
<ImageButton
android:id="@+id/share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_menu_share"
/>
</LinearLayout>