其他分享
首页 > 其他分享> > 如何在Android中设置样式的引力?

如何在Android中设置样式的引力?

作者:互联网

我有一个水平线性布局的textview,并且textview是顶部对齐的.我希望它垂直对齐.

我将textview设置为一种称为“箭头”的样式

<style name="arrow">
    <item name="android:textSize">30sp</item>
    <item name="android:textColor">#ffffff</item>
    <item name="android:textStyle">bold</item>
    <item name="android:gravity">center</item>
    <item name="android:layout_gravity">center</item>
    <item name="android:layout_width">wrap_content</item> 
    <item name="android:layout_height">wrap_content</item> 
</style>

爪哇

            LinearLayout LL = new LinearLayout(this);
            LL.setOrientation(LinearLayout.HORIZONTAL);
            LL.setPadding(15, 15, 15, 15);
            LinearLayout.LayoutParams courseMargin = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            courseMargin.setMargins(5, 5, 5, 5);
            LL.setLayoutParams(courseMargin);

                            // here I add more things into LL...

            TextView arrow = new TextView(this);
            arrow.setText(">");
            arrow.setTextAppearance(this, R.style.arrow);
            LL.addView(arrow);

但是,这仍然不能使其垂直对齐…

有人知道这是怎么回事吗?

谢谢

解决方法:

setTextAppearance()的javadocs状态:

Sets the text color, size, style, hint color, and highlight color from
the specified TextAppearance resource.

其中不包括任何有关位置或重力的信息.我想这就是为什么你的引力没有作用的原因.

尝试这样:

//for android:gravity
arrow.setGravity(Gravity.CENTER);

//for android:layout_gravity
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity=Gravity.CENTER;
arrow.setLayoutParams(params);

就是说,由于您的TextView的宽度和高度为WRAP_CONTENT,因此android:gravity不会产生任何影响.因此,实际上android:layout_gravity代码块应该是您所需要的.

标签:android-linearlayout,android,textview
来源: https://codeday.me/bug/20191122/2061299.html