允许用户在android应用中插入图片

问题描述 投票:8回答:2

我的问题是:如何创建imageButton,以允许用户从手机上载图像并将其作为图片配置文件插入应用程序?例如whatsapp,它允许用户从手机中选择图片并将其设置为图片个人资料。

谢谢

android android-widget android-imageview android-image
2个回答
9
投票

这里是以下链接。

create image button

上传图片

example 1

example 2

example 3


1
投票

我的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">

<ImageView
    android:id="@android:id/icon"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:onClick="selectImage"
    />

我的文件

public class Test extends AppCompatActivity {
private static final int SELECT_PICTURE = 0;
private ImageView imageView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    imageView = (ImageView) findViewById(android.R.id.icon);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        Bitmap bitmap = getPath(data.getData());
        imageView.setImageBitmap(bitmap);
    }
}

private Bitmap getPath(Uri uri) {

    String[] projection = {MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String filePath = cursor.getString(column_index);
   // cursor.close();
    // Convert file path into bitmap image using below line.
    Bitmap bitmap = BitmapFactory.decodeFile(filePath);

    return bitmap;
}

private void selectImage() {

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}

}
© www.soinside.com 2019 - 2024. All rights reserved.