当我单击时,按钮库打开,我选择了图像,但图像并没有显示在第二个活动中。几天来我一直在努力,但没有结果。请帮我查完整的代码。这是我的密码:
活动1
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
public class HomepageActivity extends AppCompatActivity {
private static final int SELECT_PHOTO = 1;
private static int RESULT_LOAD_IMAGE = 1;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
ImageButton buttonLoadImage = findViewById(R.id.btnphoto);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/*");
startActivityForResult(gallery, RESULT_LOAD_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO) {
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
if (selectedImage != null) {
Intent gallery = new Intent(HomepageActivity.this, ImageActivity.class);
Bundle extras = new Bundle();
extras.putString("image", selectedImage.toString());
gallery.putExtras(extras);
startActivity(gallery);
}
}
}
}}```
Activity 2
公共类imageactivity扩展了appcompatactivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
Bundle extras = getIntent().getExtras();
String name = extras.getString("image");
Uri imageFinal=Uri.parse(name);
}}```
2条答案
按热度按时间a9wyjsp71#
在imageactivity oncreate方法中
decodeuri是一种示例方法(仅适用于工作代码),用于调整图像大小,将其转换为位图并设置为imageview。如果图像大小很大,您可能会
java.lang.RuntimeException: Canvas: trying to draw too large(168709632bytes) bitmap.
```public static Bitmap decodeUri(Context c, Uri uri, final int requiredSize)
throws FileNotFoundException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri), null, o);
}
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GalleryImageActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
if (requestCode == RESULT_LOAD_IMAGE)
xzv2uavs2#
尝试将图像转换为字节数组,然后将其传递给下一个活动(如bytearray)并使用它。