0

forループを使用して一連のimagebuttonに同じ画像リソースを設定するにはどうすればよいですか?

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);
    }
}

上記のコードでエラーが発生しますb[i]

式の型は配列型でなければなりませんが、int に解決されました

4

1 に答える 1

2

以下を試してください。ImageButton が初期化されていません

   ImageButton b[];    

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);        
}

また、レイアウトのルート ビューにボタンを追加することも忘れないでください。

例:

プログラムでレイアウトを設定することもできます。線形レイアウトまたは相対レイアウトを使用して、レイアウト パラメータを設定できます。Imagebuttons をレイアウトに追加し、コンテンツをアクティビティに設定します。

必要に応じて以下を変更します。

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
       }
  }
} 
于 2013-06-08T04:48:02.733 に答える