以编程方式设置的ImageViews不会出现android

时间:2014-01-27 19:05:42

标签: android imageview

我在res / values / strings.xml中有一个整数数组,如下所示:

<integer-array name="test">

    <item>@drawable/ic_launcher</item>
    <item>@drawable/ic_launcher</item>
    <item>@drawable/ic_launcher</item>
    <item>@drawable/ic_launcher</item>
    <item>@drawable/ic_launcher</item>

</integer-array>

我想以编程方式创建一组图像按钮,但是当我使用setImageResource(forimageview [i])时,无法看到图像。

我的MainActivity类:

public class MainActivity extends Activity {
int [] forimageview ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    addchild();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


private void addchild(){
    Resources res = getResources();
    forimageview = res.getIntArray(R.array.test);
    LinearLayout linearlayout = (LinearLayout)findViewById(R.id.mylayout);
    for(int i = 0 ; i < forimageview.length ; ++i){

        ImageButton imagebutton = new ImageButton(getApplicationContext());
        imagebutton.setId(i+1);

        LinearLayout.LayoutParams imageparams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        imagebutton.setScaleType(ImageView.ScaleType.MATRIX);
        imagebutton.setImageResource(forimageview[i]);
        imagebutton.setOnClickListener(new View.OnClickListener() {

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

            }
        });
        linearlayout.addView(imagebutton, imageparams);

    }       



}

}

结果:

enter image description here

编辑:

我的布局:

<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<LinearLayout 
    android:id="@+id/mylayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >


</LinearLayout>

</RelativeLayout>

1 个答案:

答案 0 :(得分:2)

我认为你定义array的方式不正确。首先,您要在strings.xml中定义它,它必须位于arrays.xml

其次,它不是int数组,而是string数组,所以它必须是这样的:

<string-array name="your_imgs">
    <item>@drawable/first</item>
    <item>@drawable/second</item>
    <item>@drawable/third</item>
</string-array>

要访问它们,只需使用以下内容:

TypedArray imgs = getResources().obtainTypedArray(R.array.your_imgs);

for (int i = 0; i < imgs.length(); i++)
  myView.setImageResource(imgs.getResourceId(i, -1));

更多关于docs中的TypedArray。