gpt4 book ai didi

java - 从图库中选择图像在 android 中不起作用

转载 作者:行者123 更新时间:2023-11-29 02:36:33 26 4
gpt4 key购买 nike

我正在尝试从图库中选择一张图片以在 ImageView 中显示,选择有效但图像没有出现在 ImageView 中,它仍然是空白的。

代码:

public class MainActivity extends AppCompatActivity {

private static final int SELECTED_PICTURE=1;
ImageView iv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

iv=(ImageView)findViewById(R.id.imageView1);

//FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//fab.setOnClickListener(new View.OnClickListener() {
//@Override
//public void onClick(View view) {
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//.setAction("Action", null).show();
//}
}//);
public void btnClick(View v){
Intent i=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECTED_PICTURE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

switch (requestCode) {
case SELECTED_PICTURE:
if(resultCode==RESULT_OK){
Uri uri=data.getData();
String[]projection={MediaStore.Images.Media.DATA};

Cursor cursor=getContentResolver().query(uri, projection, null, null, null);
cursor.moveToFirst();

int columnIndex=cursor.getColumnIndex(projection[0]);
String filePath=cursor.getString(columnIndex);
cursor.close();

Bitmap yourSelectedImage=BitmapFactory.decodeFile(filePath);
Drawable d=new BitmapDrawable(yourSelectedImage);

iv.setBackground(d);

}
break;

default:
break;
}
}
}

我做错了什么?

最佳答案

试试下面的代码;

iv.setImageBitmap(yourSelectedImage);

而不是下面的代码;

 Drawable d=new BitmapDrawable(yourSelectedImage);
iv.setBackground(d);

关于java - 从图库中选择图像在 android 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46680945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com