将 TextView 对齐到 LinearLayout 的顶部

Align TextViews to top of LinearLayout

我正在创建一个在 LinearLayout 中有四个不同 TextView 的应用程序。 LinearLayout 的权重总和为 4,每个 TextView 的权重为 1(以使它们具有均匀的宽度)。 我的第一个问题是两个 TextViews 的高度比其他两个高,这使它们居中,但我希望它们与 LinearLayout 顶部对齐,因此所有 TextViews 都有一条直线。

我的第二个问题是其中一个字符串比 TextView 的宽度长,这使得 TextView 稍微向下(它甚至不再居中并且在 LinearLayout 父级之外,所以所有的 TextView宽度未显示)。

我的代码:

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

post xml 代码...但在我看来,您没有将高度或宽度设置为 0dp(如果是垂直则高度 layout/width 如果水平)...另外,请确保您所有的 textView 都具有 android:singleLine="true" 属性

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