简体   繁体   English

TextView setGravity()在java中不起作用

[英]TextView setGravity() doesn't work in java

I'm stuck on a problem and I don't know, what causes it. 我遇到了问题我不知道是什么原因造成的。 I have a very simple Layout like this: 我有一个非常简单的布局,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
    android:id="@+id/my_text_view"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_gravity="NOTE_THIS"
    android:textColor="#FFFFFF"
    android:textSize="22dp"
    android:text="TestText"/>
</LinearLayout>

which is included inside another layout. 它包含在另一个布局中。 If I change the gravity inside the xml I see same Result in Layout-Editor and on my phone. 如果我改变xml内部的重力,我会在Layout-Editor和手机上看到相同的结果。 If I wanna apply the Gravity programatically like with myTextView.setGravity(Gravity.CENTER) it doesn't Change anything. 如果我想以编程方式应用Gravity,就像myTextView.setGravity(Gravity.CENTER)一样,它不会改变任何东西。 And I cannot set LayoutGravity in Java on a TextView 我不能在TextView上用Java设置LayoutGravity

I'll tried for debug purposes to include them three times each with another gravity which does work even. 我会尝试将调试目的包括在内,每次使用另一个重力,它甚至可以工作。 So I assume everything is alright with my Layout and there has to be a Bug or something else I miss. 所以我认为我的布局一切都没问题,并且必须有一个Bug或其他我想念的东西。 Can someone give me a hint what I also can try, or what causes this problem? 有人可以给我一个提示,我也可以尝试,或者是什么原因导致这个问题?

将TextView的宽度设置为android:layout_width="fill_parent"然后可以使用myTextView.setGravity(Gravity.CENTER)编程方式设置它

You need to set the gravity of the LayoutParams object instead of the View itself: 您需要设置LayoutParams对象的重力而不是View本身:

TextView tv = new TextView(getApplicationContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
lp.gravity = Gravity.CENTER;
tv.setLayoutParams(lp);

当你使用LinearLayout作为父级时,layout_gravity会出现在控件中但不控制内容的图片中,所以使用android:layout_gravity使用android:gravity

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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