K
K
Konstantin Lipatov2018-06-25 12:37:19
Android
Konstantin Lipatov, 2018-06-25 12:37:19

How to set up the correct display of the image when the imageView is created programmatically?

I have a TableLayout in which I need to display an ImageView and a TextView on the same line.
I create all view elements programmatically, and when creating an ImageVIew I specify the dimensions of 130x130 pixels, but for obvious reasons, pictures are displayed differently on different devices. How can I size an ImageView so that it displays correctly on all devices?
Item creation code:

for (int i = 0; i < mainParCount; i++) {
            tableRow = new TableRow(getContext());
            tableRow.setLayoutParams( new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

            textView = new TextView(getContext());
            textView.setId(1000+i);
            int current_text_res_id = getStrResFromId(textView.getId(), "main_par_", "string");
            textView.setText(getString(current_text_res_id));
            textView.setTextSize(25);
            textView.setOnClickListener(this);
            textView.setPadding(8,8,8,8);
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setLines(2);

            ImageView imageView = new ImageView(getContext());
            imageView.setId(2000+i);
            imageView.setLayoutParams(new TableRow.LayoutParams(130, 130));
            int current_image_res_id = getImageResFromId(imageView.getId(), "imageicon", "drawable");

            imageView.setImageResource(current_image_res_id);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setPadding(8, 0,8, 0);

            tableRow.addView(imageView);
            tableRow.addView(textView);
            tableRow.setGravity(Gravity.CENTER);

            tableLayout.addView(tableRow, i);
            tableLayout.setColumnShrinkable(i, true);
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-06-25
@Weys

1. make up a cell and inflate it by filling it with content.
2. think about whether you can get by with some kind of List / recucler-View with an adapter.
3. google how to pass non-absolute numbers to layout parameters :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question