以编程方式使CustomFontTextView居中

时间:2019-06-17 12:31:52

标签: android text-styling

以某种方式我无法将CustomTextView小部件文本居中,这应该是一行代码。

LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(0, height, 1);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(linearLayoutParams);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER);
masterLinearLayout.addView(linearLayout);

LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textViewParams.gravity = Gravity.CENTER_HORIZONTAL;

CustomFontTextView valueTextView = new CustomFontTextView(this);
valueTextView.setLayoutParams(textViewParams);
valueTextView.setTextAppearance(this, R.style.CoolStyle);
valueTextView.selectCustomFont(getString(R.string.default_regular_font));
linearLayout.addView(valueTextView);

还有我的syle“ CoolStyle”:

<style name="CoolStyle" parent="@android:style/TextAppearance.Medium">
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textSize">@dimen/..</item>
        <item name="android:layout_marginTop">10dp</item>
        <item name="android:layout_margin">3dip</item>
        <item name="android:gravity">center_horizontal</item>
        <item name="android:layout_gravity">center_horizontal</item>
        <item name="android:singleLine">true</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
</style>

奇怪的是-textColoring和textSize实际上有效,但是我似乎无法将文本居中并使其成为单个文本行。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

首先,检查父级LinearLayout,是否具有完整宽度。其次,您可以通过编程将layout_width textView设置为WRAP_CONTENT,但是样式具有相反的MATCH_PARENT。然后,您要为 textViewParams 设置textAppearance,它不会影响任何内容。尝试设置其布局并赋予适当的重力。