以编程方式设置ImageButton图像

时间:2015-11-10 21:32:19

标签: java android

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

这是我的代码:

__author__ = 'Luca Sorrentino'


numbers = open("Numbers", 'r+')
numbers.truncate() #OPENS THE FILE AND DELETES THE PREVIOUS CONTENT
                    # Otherwise it prints out all the inputs into the file ever

numbers = open("Numbers", 'a')  #Opens the file so that it can be added to
liist = list() #Creates a list called liist

def entry(): #Defines a function called entry, to enable the user to enter numbers
        try:
            inputt = float(input("Please enter a number"))  #Stores the users input as a float in a variable
            liist.append(inputt) #Appends the input into liist
        except ValueError: #Error catching that loops until input is correct
            print("Please try again. Ensure your input is a valid number in numerical form")
            entry() #Runs entry function again to enable the user to retry.

x = 0
while x < 4:  # While loop so that the program collects 4 numbers
    entry()
    x = x + 1

for inputt in liist:
  numbers.write("%s\n" % inputt) #Writes liist into the text file


numbers.close() #Closes the file

numbers = open("Numbers", 'r+')

output = (numbers.readlines())

my_list = list()
my_list.append(output)

print(my_list)
print(my_list[1])

3 个答案:

答案 0 :(得分:1)

  

将其设置为该按钮的图像

轻松!使用public void setImageBitmap (Bitmap bm)

  

代码仅在从“照片”

中检索图像时有效

您的代码将失败,因为存储在Google照片/驱动器等应用中的图片具有光标无法解析的不同类型的路径。

将您的getPath()方法更改为

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri     The Uri to query.
 */
@TargetApi(19)
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

答案 1 :(得分:1)

也许有帮助:

   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);
            }
        }
    }

答案 2 :(得分:1)

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
                b1.setBackground(new BitmapDrawable(getResources(), bitmap));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}