Jochen Birkle
Jochen Birkle

Reputation: 335

Strange beavior with LayoutParams

I am currently playing around a bit with code generated Layouts. There I recogniced a problem in this part of code:

dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int dp_x = (dm.widthPixels - 32) / 10;

for(int x = 0; x < 9; x++) {
    TableRow tr = new TableRow(this);
    tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 
                                        LayoutParams.WRAP_CONTENT));
    for(int y = 0; y < 9; y++) {
        ImageView i = new ImageView(this);
        i.setClickable(true);
        i.setLayoutParams(new LayoutParams(dp_x, dp_x));
        i.setScaleType(ScaleType.FIT_XY);
        i.setImageDrawable(getResources().getDrawable(R.drawable.i0));
        iv[x][y] = i;
        tr.addView(iv[x][y]);
    }
    fieldLayout.addView(tr);
}

Especially this line seems to cause the problem:

i.setLayoutParams(new LayoutParams(dp_x, dp_x));

When this line is commented out everything is displayed correctly. But as soon as I uncomment it not a single one of the ImageViews is displayed. I looked into debugging and every value seems to be added correctly to the ImageView. Any Idea, what causes this error?

Another thing is - I know DisplayMetrics and their width/height are discouraged to use. Here I use it to scale the ImageViews in dependence to the display. Can I achieve this in another way, too?

Upvotes: 0

Views: 74

Answers (1)

Danish Ashfaq
Danish Ashfaq

Reputation: 446

Assuming your dp_x and dp_y values are correct :

TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(dp_x, dp_y);
i.setLayoutParams(layoutParams);

It seems like it doesn't change anything but it worked for me ! Maybe because the LayoutParams are more specific (TableRow.LayoutParams)

Hope this helps !

Upvotes: 1

Related Questions