简体   繁体   中英

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);

发布xml代码...但是在我看来,您没有将高度或宽度设置为0dp(如果是垂直布局则为高度,如果是水平则为宽度)...此外,请确保所有textViews都具有android :singleLine =“ true”属性

由于每个用户仅需要根据他们所属的组查看这些TextView之一,因此我将其设置为用户设置,并仅显示该用户的正确TextView。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM