2013-02-27 116 views
2

为了设置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 托比亚斯

+1

Wh在是错误? (Logcat) – Bigflow 2013-02-27 13:02:11

+0

你能解释一下你想用B做什么吗? – bofredo 2013-02-27 13:04:41

+0

嗨,对不起,我必须使用列表而不是数组。对不起我的不必要的问题。我应该删除这个不必要的问题吗?托比亚斯 – CoUnt3r 2013-02-27 13:19:27

回答

7

ImageView[] IMGS = { iv1, iv2, iv3 };只包含在目前3个空元素,你是循环

尝试添加在你的IMGS中做的值

IMGS[0] = iv1; 
IMGS[1] = iv2; 
IMGS[2] = iv3; 
6
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到阵列