最近做了一个小软件,想实现动态替换背景图片的效果,查找资料半天才实现哭,下面是代码:
随便给了一个ImageView,通过点击图片来更换背景
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/photo"
android:src="@drawable/ic_launcher"
/>
后台的实现
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.photo:
showChoosePhotoDialog();
break;
default:
break;
}
}
private void showChoosePhotoDialog() {
CharSequence[] items = { "相册", "相机" };
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("选择图片来源")
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (which == SELECT_PICTURE) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, SELECT_CAMER);
} else {
Intent intent = new Intent(
Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PICTURE);
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
}).create();
dialog.show();
}
//选择图片或拍完照片之后触发
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);//用ContentProvider查找选中的图片
cursor.moveToFirst();
String path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));//获取图片的绝对路径
// 获取手机屏幕的像素
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
Resources s = getResources();
setBackGround(path,dm,s);
cursor.close();
} else {
Toast.makeText(DialogActivity.this, "选择图片失败,请重新选择", Toast.LENGTH_SHORT)
.show();
}
}
//设置背景图片
public void setBackGround( String path, DisplayMetrics dm,Resources s){
File imageFile=new File(path);
Drawable drawable= Drawable.createFromPath(path);
BitmapDrawable bd = (BitmapDrawable) drawable;
bmp = bd.getBitmap();
//压缩图片
bmp = Bitmap.createScaledBitmap(bmp, dm.widthPixels, dm.heightPixels, true);
Log.i("wechat", "压缩后图片的大小" + (bmp.getByteCount()/ 1024 / 1024 ) + "M宽度为"
+ bmp.getWidth() + "高度为" + bmp.getHeight());
CarInsuranceActivity.layout.setBackground(new BitmapDrawable(s, bmp));
}
初学android,有不对的地方望指出