简体   繁体   中英

How do I Load ImageButton image at runtime from SD Card?

I want to let the user to load their own images from an SD Card to be used as an ImageButton. Here is my main.xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/heart"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <ImageButton
        android:id="@+id/imageButton2"
        android:layout_width="150dp"
        android:layout_height="200dp"
        android:src="@drawable/me" />

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="150dp"
        android:layout_height="200dp"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="50dp"
        android:cropToPadding="true"
        android:scaleType="fitCenter"
        android:src="@drawable/mylove" />

</LinearLayout>

In the onCreate method of your java-code assign the button to a variable, and then set a resource or Bitmap which will be decoded from a file using the BitmapFactory class.

Bitmap bmp = BitmapFactory.decodeFile("path/to/file");
ImageButton button1 = (ImageButton)findViewById(R.id.imageButton1);
button1.setImageBitmap(bmp);

Try like this

  ImageButton img = (ImageButton)findViewById(R.id.imageButton2);
  Bitmap bmp = BitmapFactory.decodeFile(path);
  img.setImageBitmap(bmp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM