简体   繁体   English

Android:如何以编程方式在水平布局中将TextView水平居中

[英]Android:How do I center TextView horizontally in LinearLayout Programatically

I have a textview view whose width doesn't cover all the parent's width. 我有一个textview视图,其宽度不能覆盖父对象的所有宽度。 I have used valueTV.setGravity(Gravity.CENTER_HORIZONTAL); 我用过valueTV.setGravity(Gravity.CENTER_HORIZONTAL);

and it puts the text in center of textview. 并将文本放在textview的中心。 Now I want to take the whole textview in the center of the parent ( which apparently covers the whole scrren). 现在,我想将整个textview放在父级的中心(显然涵盖了整个scrren)。 How can it be done programatically. 如何以编程方式完成。 I want to align the textview to center.Basically I know a lot of questions have already been asked which are quite similar to this but not exactly the same as they didnot solve my problem. 我想使textview居中对齐。基本上我知道已经问了很多问题,这些问题与此非常相似,但由于不能解决我的问题而并不完全相同。

// Make sure textview width match parent
// Use param: ViewGroup.LayoutParams.MATCH_PARENT

LinearLayout.LayoutParams layoutParams = 
  new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

// Make sure text is center
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;

linearLayout.addView(valueTV, layoutParams);

Hmmm... Try this perhaps 嗯...尝试一下

TextView tv = findViewById(R.id.yourTextView);
LinearLayout.LayoutParams layoutParams = 
(LinearLayout.LayoutParams)tv.getLayoutParams();
 layoutParams.gravity = Gravity.CENTER_HORIZONTAL;

tv.setLayoutParams(layoutParams);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM