作者:刘诗宪668964 | 来源:互联网 | 2023-05-22 11:14
I know this question has been asked many times on SO. I have read most of them, but they don't work for me, so don't bother marking duplicates.
我知道这个问题已多次被问过。我已经阅读了大部分内容,但它们对我不起作用,所以不要打扰重复标记。
Here is my code, and what I have tried so far:
这是我的代码,到目前为止我尝试过的:
RelativeLayout cOntainer= new RelativeLayout(this.getContext());
TextView tv = new TextView(this.getContext());
tv.setText(txt); // a single digit like '3'
tv.setLines(1);
tv.layout(0, offsety, cellszie, offsety+cellsize);
tv.setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER);
tv.setGravity(Gravity.CENTER);
// I also tried CENTER_VERTIAL and the following line
// tv.setGravity(CENTER_VERTIAL| CENTER_HORIZONTAL);
// I also tried giving LayoutParams to tv like this:
// tv.setLayoutParams(new LayoutParams(cellsize, cellsize));
// tv.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
// tv.setLayoutParams(new LayoutParams(MATCH_PARENT, MATCH_PARENT));
container.addView(tv);
The character is horizontally centered, but it floats on the top of the TextView vertically. Setting gravity
and LayoutParams
doesn't change its behavior.
字符水平居中,但它垂直浮动在TextView的顶部。设置gravity和LayoutParams不会改变其行为。
What should I do to make it center vertically?
我该怎么办才能让它垂直居中?
3 个解决方案