gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:07:05 25 4
gpt4 key购买 nike

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

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);
}
}

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

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

最佳答案

好的..所以我想通了。我只需要在每个 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);

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

关于android - 自定义 View 中 RelativeLayout 内的 Textview 没有正确应用重力?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6222954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com