自定义View中RelativeLayout内的Textview没有正确应用重力?

Joi*_*dio 6 android view gravity textview

所以我有一个设置,我正在创建自己的视图,我正在添加一些TextViews.但是,重力设置被打破了.(它水平居中,但不是垂直居中)我这样做是因为除了TextView之外我还在其他视图中绘制其他东西,但这些工作正常.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Joi*_*dio 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);
Run Code Online (Sandbox Code Playgroud)

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