0

In some part of my application I need to set explicitly the height of a layout.

I have this code for that:

    ListView.LayoutParams lp = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, getListViewHeight(questionsList));
ListView.LayoutParams.WRAP_CONTENT);
    final LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    final ListView questionView = new ListView(activity);
    questionView.setId(generateViewId());
    QuestionAdapter questions = new QuestionAdapter(activity, new ArrayList<TdcQuestion>(Arrays.asList(questionsList)));
    questionView.setAdapter(questions);
    questionView.setLayoutParams(lp);
    layout.setLayoutParams(ll);
    layout.addView(questionView);

The method that calculates height for lp layout is:

private static int getListViewHeight(TdcQuestion[] questions)
{
    int height = (questions.length - 1) * 7;  // Suma al alto las separaciones entre los ítemes de la lista
    for (int i = 0; i < questions.length; i++) {
        String tipo = questions[i].getType().getName();

        if (tipo.equals("RADIO"))
            height += 212;
        else if (tipo.equals("CHECK"))
            height += 212;
        else if (tipo.equals("NUM"))
            height += 265;
        else if (tipo.equals("TEXT"))
            height += 433;
        else if (tipo.equals("PHOTO"))
            height += 85;
        if (questions[i].hasPhoto())
            height += 182;
    }

    return height;
}

The problem is that in my Samsung S6 it is shown perfectly, this way:

Layout in my Samsung S6

However, in customer's phone (an Alcatel One Touch Mini S), it is shown this way:

enter image description here

The button whose label is "Modelo de BRs" appears a lot of pixels below.

I have created an emulator device with the same screen size of customer's phone, and the same happens, so, this has to do directly with screen size. How can I solve it?

One more fact. My phone is Android 5.1.1, while customer's phone has Android 4.2.2 (API 18), but the application is being compiled for API 15 to make it more compatible.

jstuardo
  • 3,901
  • 14
  • 61
  • 136

1 Answers1

2

In your getListViewHeight() method, i see a bunch of numbers. LayoutParams lets you set Height and Width in terms of PIXELS. Hence you have designed those bunch of numbers for a particular device as they are just PIXELS. What you need to do is set them as dp or independent pixels.

How you convert dp to pixels using display metrics is shown here: https://stackoverflow.com/a/5960030/4747587

So now, instead of going ahead with pixel values, use dp values instead. This will make sure, you have the same height in all devices with different densities.

Community
  • 1
  • 1
Henry
  • 17,490
  • 7
  • 63
  • 98