Search code examples
androidandroid-layoutalignmentandroid-linearlayouttextview

Align TextViews to top of LinearLayout


I'm creating an app that has four different TextView inside a LinearLayout. The LinearLayout has a weight sum of 4 and every TextView has a weight of 1 (to make them with evenly width). My first problem is that two of the TextViews has a bigger height than the other two and this make them centered but I want them to be top aligned to the LinearLayout so all of the TextViews have a straight line.

My second problem is that one of the strings is longer than the width of the TextView, which makes that TextView go slightly downward (it is not even centered anymore and is outside of the LinearLayout parent, so all of the TextView width is not shown).

My code:

        LinearLayout layout = new LinearLayout(context);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        layout.setLayoutParams(layoutParams);
        layout.setWeightSum(lessons);

        for (int i = 0; i < lessons; i++) {
            TextView text = new TextView(context);
            LayoutParams textParams = new LayoutParams((int) (0 * (context.getResources().getDisplayMetrics().density) + 0.5f),
                    (int) (length[i] * (context.getResources().getDisplayMetrics().density) + 0.5f), 1);
            text.setLayoutParams(textParams);

            System.out.println(length[i]);

            text.setPadding((int) (8 * (context.getResources().getDisplayMetrics().density) + 0.5f), 0, 0, 0);
            text.setTextColor(context.getResources().getColor(R.color.white_text));
            text.setBackgroundColor(context.getResources().getColor(R.color.class.getField(name[i]).getInt(null)));
            text.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            text.setGravity(Gravity.CENTER_VERTICAL);
            text.setText(R.string.class.getField(name[i]).getInt(null));

            layout.addView(text);
        }

        week[day].addView(layout);

Solution

  • Since every user only needs to see one of those TextViews based on which group they belong to I will make it a user setting and only show the correct TextView for that user.