6

所以我有一个设置,我正在创建自己的视图,并在其中添加一些 TextView。但是,它的重力设置被破坏了。(它水平居中,但不是垂直居中)我这样做是因为除了 TextViews 之外,我还在我的视图中绘制了其他东西,但那些工作正常。TextView 的重力只有一个问题。这是我所拥有的部分代码。

public class myView extends View {

    protected RelativeLayout baseLayout;
    protected TextView textView1;
    protected TextView textView2;

    public myView (Context context) {
        super(context);
        setLayoutParams(new LayoutParams(FILL_PARENT, FILL_PARENT));

        baseLayout = new RelativeLayout(context);
        baseLayout.setLayoutParams(new LayoutParams(FILL_PARENT, FILL_PARENT));

        textView1 = new TextView(context);
        // initialize textView1 string, id, textsize, and color here
        textView2 = new TextView(context);
        // initialize textView2 string, id, textsize, and color here

        baseLayout.addView(textView1);
        baseLayout.addView(textView2);
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Resources res = getResources();
        // calculate out size and position of both textViews here
        textView1.layout(left1, top1, left1 + width1, top1 + height1);
        textView1.setGravity(Gravity.CENTER);
            textView1.setBackgroundColor(green); // just to make sure it's drawn in the right spot
        textView2.layout(left2, top2, left2 + width2, top2 + height2);
        textView2.setGravity(Gravity.CENTER);
            textView2.setBackgroundColor(blue); // same as above

        baseLayout.draw(canvas);
    }
}

这会将 TextViews 绘制在我想要它们的确切位置和大小(我知道是因为背景颜色),但重力将它们设置为仅水平居中..而不是垂直居中。(是的,TextView 比实际的文本字符串大)

我可能可以实现此处找到的解决方案(TextView 重力),但这似乎不是解决此问题的一种非常有效或可靠的方法。我做错了什么导致重力停止正常工作吗?任何输入/帮助表示赞赏。

4

3 回答 3

9

好的..所以我想通了。我只需要在每个 TextView 上运行 measure() 方法。所以我的新代码如下所示:

    textView1.measure(MeasureSpec.makeMeasureSpec(width1, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height1, MeasureSpec.EXACTLY));
    textView1.layout(left1, top1, left1 + width1, top1 + height1);
    textView1.setGravity(Gravity.CENTER);

    textView2.measure(MeasureSpec.makeMeasureSpec(width2, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height2, MeasureSpec.EXACTLY));
    textView2.layout(left2, top2, left2 + width2, top2 + height2);
    textView2.setGravity(Gravity.CENTER);

现在它像它应该的那样水平和垂直居中。如果您遇到同样的问题,请尝试一下。

于 2011-06-03T23:44:50.320 回答
2

您可以像这样使用 setGravity 设置多个重力参数。

textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL );

看看如何在 Android 的 TextView 中水平和垂直居中文本?

于 2011-06-03T05:20:58.580 回答
0

我也遇到了这个问题。我的问题是,当我通过调用 TextView.setGravity() 在 TextView 上设置重力时,它会默默地影响父视图中自身(Textview)的布局。

这是我为解决方法修复所做的:

TextView schedule = getBubbleTextView (item, hasZeroSpanEvent);
// There's a bug in TextView, we need to use wrapper to fix it   
LinearLayout wrapper = new LinearLayout (getApplicationContext ());
wrapper.addView (schedule); 
hourlyBubbleParent.addView (wrapper, llp);

您应该抓住应该使用包装器来解决此问题的想法。

于 2013-05-27T11:03:59.530 回答