以编程方式将数组的图像按钮放在视图上

时间:2013-03-09 22:28:55

标签: java android

我对imagebutton数组有疑问。我想通过在RelativeLayout中更改marginTop和marginLeft,以编程方式将数组的每个图像按钮放在不同的位置。这是我的代码,但它只显示同一位置上的所有图像按钮,就像它们没有边距一样:

DatabaseHandler db;
db= new DatabaseHandler(this);
int databasereadercount=db.getMemoryCount();

ImageButton[] button= new ImageButton[60];
setContentView(R.layout.playsolo);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.playsololayout);
for(int i=0;i<60;i++){
if(i<=databasereadercount){
    button[i]=new ImageButton(this);
    FrameLayout.LayoutParams[] params = new FrameLayout.LayoutParams[60];
    params[i]=new FrameLayout.LayoutParams(100,100);
    params[i].setMargins(10*i, 5*i, 0, 0);       //for example
    Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.raster);
    bitmap=Bitmap.createScaledBitmap(bitmap, 480, 320, true);
    Drawable drawable = new BitmapDrawable(getResources(),bitmap);
    StateListDrawable states = new StateListDrawable();
    states.addState(new int[] {android.R.attr.state_pressed},drawable);
    states.addState(new int[] {android.R.attr.state_focused},drawable);
    states.addState(new int[] { },drawable);
    button[i].setImageDrawable(states);
    button[i].setId(i);
    button[i].setOnClickListener(new View.OnClickListener(){
    public void onClick(View v) {
            // TODO Auto-generated method stub
        startlevel(v.getId());
        }
    });
    layout.addView(button[i],params[i]);

    }
}

1 个答案:

答案 0 :(得分:2)

当您的布局为FrameLayout.LayoutParams时,您正在使用RelativeLayout。如果我没有完全弄错,你应该使用RelativeLayout.LayoutParams代替。