【问题标题】:Set an ImageView in Android from Array从数组中设置 Android 中的 ImageView
【发布时间】:2026-01-21 14:35:01
【问题描述】:

我刚开始使用 android,我正在尝试将 ImageView 资源设置为数组中的 id(从另一个活动传递)。

这是活动代码的相关部分:

Bundle extras = getIntent().getExtras(); 
int bNumber = extras.getInt("number");

Resources res = getResources();
int[] bLogos = res.getIntArray(R.array.bLogos);
int cImage = bLogos[bNumber];
ImageView imageLayout = (ImageView)findViewById(R.id.image);
imageLayout.setImageResource(cImage);

这是相关的活动布局:

<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="0dp"
android:paddingTop="0dp" />

这是数组:

<array name="bLogos">
<item>@drawable/logo1</item>
<item>@drawable/logo2</item>
<item>@drawable/logo3</item>
</array>

问题是我的 setImageResource 没有进行仿真,drawable 没有加载。而且 Eclipse 没有告诉我代码中有任何错误。

任何帮助将不胜感激。

【问题讨论】:

    标签: android arrays imageview int


    【解决方案1】:

    Log.e("asd", "cImage: " + cImage); 添加到您的代码中。你会发现cImage总是0。不要使用 xml 文件来存储图片的 id。它不起作用。更改您的代码如下:

    Bundle extras = getIntent().getExtras(); 
    int bNumber = extras.getInt("number");
    
    int[] bLogos = {R.drawable.logo1, R.drawable.logo2, R.drawable.logo3};
    int cImage = bLogos[bNumber];
    ImageView imageLayout = (ImageView)findViewById(R.id.image);
    imageLayout.setImageResource(cImage);
    

    【讨论】: