gpt4 book ai didi

java - 以编程方式设置 ImageButton 图像

转载 作者:行者123 更新时间:2023-12-01 22:00:20 24 4
gpt4 key购买 nike

当我单击 ImageButtonit 时,它提示我从设备中选择一个图像,然后我的目的是将其设置为该按钮的图像。此外,该代码仅在从“照片”检索图像时才有效,因此如果我可以获得一些关于如何使其适用于所有选项的提示,这将是很棒的。

这是我的代码:

package lucas.app_2001;


import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;


public class Shout extends AppCompatActivity {
ImageButton b1;
private static final int SELECT_PICTURE = 1;
String selectedImagePath;
RelativeLayout myLayout1;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shout);
b1 = (ImageButton) findViewById(R.id.imageButton);
myLayout1 = (RelativeLayout) findViewById(R.id.myLayout1);
findViewById(R.id.imageButton);
b1.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {

// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);

b1.setImageResource(selectedImageUri);
}
}
}

/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri contentUri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
}

最佳答案

也许有帮助:

   public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagePath);
b1.setImageBitmap(myBitmap);
}
}
}

关于java - 以编程方式设置 ImageButton 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33640002/

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