我有一个设置,我正在创建自己的View,并在其中添加一些TextView。但是,它的gravity设置已经失效了。(水平居中,但垂直方向不居中)我这样做是因为除了TextView之外,我还在我的视图中绘制其他东西,但这些都正常工作。只有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(我知道这是因为背景颜色),但是重力只将它们水平居中,而不是垂直居中。(是的,TextView比实际文本字符串要大)。
我可以尝试实现此处找到的解决方案(TextView gravity),但这似乎不是一个非常高效或可靠的方法来解决这个问题。是否有什么我做错了导致重力无法正常工作?任何输入/帮助都会受到赞赏。