如何设置ImageView []数组?

时间:2013-02-27 12:59:02

标签: android arrays imageview

为了设置ImageView动态我采用了ImageView []数组。如果我尝试从我的数组中处理ImageView,则活动崩溃。我的错误在哪里?

activity_main.xml中:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" >

    <ImageView
        android:id="@+id/iv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitStart" />

    <ImageView
        android:id="@+id/iv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitStart" />

    <ImageView
        android:id="@+id/iv3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitStart" />
</TableRow>

</RelativeLayout>

MainActivity.java:

    package com.example.test;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ImageView;

    public class MainActivity extends Activity {

    private ImageView iv1, iv2, iv3;
    private ImageView[] IMGS = { iv1, iv3, iv3 };

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

    iv1 = (ImageView) findViewById(R.id.iv1);
    iv2 = (ImageView) findViewById(R.id.iv2);
    iv3 = (ImageView) findViewById(R.id.iv3);

    setImages();
}

private void setImages() {

    // A) this works
    iv1.setImageResource(R.drawable.ic_launcher);
    iv2.setImageResource(R.drawable.ic_launcher);
    iv3.setImageResource(R.drawable.ic_launcher);

    // B) at the beginning i need to set all images in a row
    for (ImageView img : IMGS) {
        img.setImageResource(R.drawable.ic_launcher);
    }

    // C) later on i need to set an particular image
    IMGS[1].setImageResource(R.drawable.ic_launcher);
}

    }

查看setImages()。一部作品,B和C使我的活动崩溃。我的错误在哪里?

TIA 托拜厄斯

3 个答案:

答案 0 :(得分:8)

您的ImageView[] IMGS = { iv1, iv2, iv3 };在循环时只包含3个空元素

尝试通过

在IMGS中添加值
IMGS[0] = iv1;
IMGS[1] = iv2;
IMGS[2] = iv3;

答案 1 :(得分:7)

protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     iv1 = (ImageView) findViewById(R.id.iv1);
     iv2 = (ImageView) findViewById(R.id.iv2);
     iv3 = (ImageView) findViewById(R.id.iv3);

     IMGS[0] = iv1;
     IMGS[1] = iv2;
     IMGS[2] = iv3;

     setImages();
}

您永远不会将iv1,iv2和iv3分配给数组

答案 2 :(得分:3)

使用以下代码,这对我有用

ImageView[] IMGS= new ImageView[3];

IMGS[0]=findViewById(R.id.iv1);
IMGS[1]=findViewById(R.id.iv2);
IMGS[2]=findViewById(R.id.iv3);