Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can i set the same image resource for a series of imagebutton using a for loop ?

ImageButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14,
        b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27,
        b28, b29, b30;

public void setresource() {
    for (int i = 0 ; i <= 15; i++){
        b[i].setImageResource(R.drawable.playzz);
    }
}

The above code give error on b[i]

The type of the expression must be an array type but it resolved to int

share|improve this question
have u initialize ImageButton – Dixit Patel Jun 8 at 4:33
what is your error.? – Segi Jun 8 at 4:33
@Segi The type of the expression must be an array type but it resolved to int – Sai Kiran Jun 8 at 4:46

1 Answer

Try the below. You have not initialized ImageButton

   ImageButton b[];    

In your onnCreate(param)

  b = new ImageButton[15]; 
  for (int i = 0 ; i <15; i++){
    b[i] = new ImageButton(ActiivtyName.this);
    b[i].setImageResource(R.drawable.playzz);        
}

Also remember to add the button to you root view of the layout.

Example:

You can also set the layout programatically. You can use use linear layout or relative layout set the layout parameters. Add the Imagebuttons to the layout and set the content to the activity.

Modify the below according to your requirements.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
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">
<LinearLayout 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/ll"
tools:context=".MainActivity" >
</LinearLayout> 
</ScrollView>

MainActivity.java

public class MainActivity extends Activity {   
ImageButton b[]; 
LinearLayout ll;
protected void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ll = (LinearLayout) findViewById(R.id.ll);// initialize linearlayout           
    setresource();
}
public void setresource()
{
       b = new ImageButton[15];
       for (int i = 0 ; i < 15; i++){
        b[i]= new ImageButton(MainActivity.this); // initilize
        b[i].setMaxWidth(40); // set the maxwidth
        b[i].setImageResource(R.drawable.ic_launcher); // set background image
        ll.addView(b[i]); // add the imagebutton to the linearlayout
       }
  }
} 
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.