所以我有一个设置,我正在创建自己的视图,并在其中添加一些 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 重力),但这似乎不是解决此问题的一种非常有效或可靠的方法。我做错了什么导致重力停止正常工作吗?任何输入/帮助表示赞赏。