1

我正在制作一个自定义布局,我想从图库中动态添加图像视图。但是,当我从图库中选择图像时,我就被逼近了。我无法得到相同背后的错误。

这是我的代码..

public class Dynamic extends Activity {
int i;
ImageView[] img_items;
ArrayList<String> values = new ArrayList<String>();
LinearLayout imageLayout;
Button btn;
private static int RESULT_LOAD_IMAGE = 1;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dynamic_load);

    imageLayout = (LinearLayout)findViewById(R.id.image_layout);
    btn = (Button)findViewById(R.id.btn_ADD);
    img_items = new ImageView[values.size()];

    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            values.add("AA");

            Intent i = new Intent(
                    Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);

        }
    });


}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        /*ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));*/


        //Creating the image layouts dynamically
        for( i=0;i<values.size();i++){

            img_items[i] = new ImageView(Dynamic.this);

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

            params.setMargins(10, 10, 0, 0);
            img_items[i].setLayoutParams(params);

        }

        img_items[i].setImageBitmap(BitmapFactory.decodeFile(picturePath));
        imageLayout.addView(img_items[i]);


    }
}
}

日志猫

10-05 16:52:03.422: D/AndroidRuntime(451): Shutting down VM
10-05 16:52:03.422: W/dalvikvm(451): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
10-05 16:52:03.549: E/AndroidRuntime(451): FATAL EXCEPTION: main
10-05 16:52:03.549: E/AndroidRuntime(451): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/1 }} to activity {com.example.dynamicloading/com.example.dynamicloading.Dynamic}: java.lang.ArrayIndexOutOfBoundsException
10-05 16:52:03.549: E/AndroidRuntime(451):  at android.app.ActivityThread.deliverResults(ActivityThread.java:3515)
10-05 16:52:03.549: E/AndroidRuntime(451):  at android.app.ActivityThread.handleSendResult(ActivityThread.java:3557)
10-05 16:52:03.549: E/AndroidRuntime(451):  at android.app.ActivityThread.access$2800(ActivityThread.java:125)
10-05 16:52:03.549: E/AndroidRuntime(451):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2063)
10-05 16:52:03.549: E/AndroidRuntime(451):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-05 16:52:03.549: E/AndroidRuntime(451):  at android.os.Looper.loop(Looper.java:123)
10-05 16:52:03.549: E/AndroidRuntime(451):  at android.app.ActivityThread.main(ActivityThread.java:4627)
10-05 16:52:03.549: E/AndroidRuntime(451):  at java.lang.reflect.Method.invokeNative(Native Method)
10-05 16:52:03.549: E/AndroidRuntime(451):  at java.lang.reflect.Method.invoke(Method.java:521)
10-05 16:52:03.549: E/AndroidRuntime(451):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-05 16:52:03.549: E/AndroidRuntime(451):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-05 16:52:03.549: E/AndroidRuntime(451):  at dalvik.system.NativeStart.main(Native Method)
10-05 16:52:03.549: E/AndroidRuntime(451): Caused by: java.lang.ArrayIndexOutOfBoundsException
10-05 16:52:03.549: E/AndroidRuntime(451):  at com.example.dynamicloading.Dynamic.onActivityResult(Dynamic.java:81)
10-05 16:52:03.549: E/AndroidRuntime(451):  at android.app.Activity.dispatchActivityResult(Activity.java:3890)
10-05 16:52:03.549: E/AndroidRuntime(451):  at android.app.ActivityThread.deliverResults(ActivityThread.java:3511)
10-05 16:52:03.549: E/AndroidRuntime(451):  ... 11 more
10-05 16:57:04.140: I/Process(451): Sending signal. PID: 451 SIG: 9
4

5 回答 5

2

您需要将i值减一,因为ifor 循环中的值是递增的,例如您有迭代5时间,因此 for 循环将是迭代5时间,以开始0和结束,4但当时i值首先增加,然后它将检查2 表达式i在那个时间i值的长度和forvalues.size()是否相同,因此它终止for循环执行其余代码

已编辑

if(i==values.size() && i>0)
   i--;

img_items[i].setImageBitmap(BitmapFactory.decodeFile(picturePath));
imageLayout.addView(img_items[i]);

i=0每次你都需要设置另一件事,onActivityResult()否则你总是得到i最后的价值

于 2012-10-05T11:36:47.867 回答
0

您在 onCreate 中初始化数组 img_items :

img_items = new ImageView[values.size()];

此时 values.size() 为“零”。

您应该在 onActivityResult 中的 for 循环之前执行此初始化:

    img_items = new ImageView[values.size()];
    for( i=0;i<values.size();i++){
    ...
于 2012-10-05T11:44:04.773 回答
0

看到代码后,我可以说,当你用 values.size() 初始化 ImageView 数组时

img_items = new ImageView[values.size()];

当时“值”Arraylist 的大小为 0,因此 ImageView 数组的大小也为 0,然后您将 ImageView 放入 onActivityResult() 中大小为 0 的数组中。

img_items[i] = new ImageView(Dynamic.this);
于 2012-10-05T11:44:55.477 回答
0

下面是从图像意图加载多个图像的代码。我从如何为我的应用程序从图库(SD 卡)中挑选图像?

  Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(
                               selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            for(int i=0;i<cursor.getCount();i++)
            {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);

            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
            ImageView img_items = new ImageView(AnimatedPopupActivity.this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
            params.setMargins(10, 10, 0, 0);
            img_items.setLayoutParams(params);

            img_items.setImageBitmap(yourSelectedImage);
            imageLayout.addView(img_items);



            cursor.moveToNext();
            }
            cursor.close();
于 2012-10-05T12:02:09.900 回答
-1

试试这个..

主要的.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Button" />

</LinearLayout>

活动课..

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

    LinearLayout mainLinearLayout;
    Button button;
      Bitmap bmp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainLinearLayout = (LinearLayout)findViewById(R.id.mainLayout);
        button = (Button)findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                openGallery();
            }
        });
    }


    private void openGallery()
    {
        Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, 1);
    }
    protected void onActivityResult(int requestCode, int resultcode, Intent intent)
    {
        super.onActivityResult(requestCode, resultcode, intent);


        if (requestCode == 1)
        {
            if (intent != null && resultcode == RESULT_OK)
            {             

                  Uri selectedImage = intent.getData();

                  String[] filePathColumn = {MediaStore.Images.Media.DATA};
                  Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                  cursor.moveToFirst();
                  int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                  String filePath = cursor.getString(columnIndex);
                  cursor.close();

                  if(bmp != null && !bmp.isRecycled())
                  {
                      bmp = null;               
                  }

                  bmp = BitmapFactory.decodeFile(filePath);

                 ImageView imageView = new ImageView(MainActivity.this);
                 imageView.setImageBitmap(bmp);
                 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(100,100);
                 imageView.setLayoutParams(lp);

                 mainLinearLayout.addView(imageView,lp);


            }
            else
            {
                Log.d("Status:", "Photopicker canceled");           
            }
        }
    }
}
于 2012-10-05T11:51:11.700 回答