开发者

Programmatically set android:layout_centerHorizontal

开发者 https://www.devze.com 2023-04-01 02:08 出处:网络
In xml you can do the following:开发者_如何学Python <TextView ... android:layout_centerHorizontal=\"true\"

In xml you can do the following:

开发者_如何学Python
<TextView
    ...
    android:layout_centerHorizontal="true"
    ...
/>

How would I, when I have the instance of TextView, do this programmatically?


You should use the addRule method of the RelativeLayout.LayoutParams class.

layoutparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
mTextView.setLayoutParams(layoutParams);


Assuming you have a TextView called stored in a variable tv:

RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tv.getLayoutParams();
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
tv.setLayoutParams(lp);

Should do the trick.


After 10 minutes of fighting I found how to do it in Kotlin:

N.B. - I am using view binding

val centerHorizontal = binding.tvOccupantName.layoutParams as RelativeLayout.LayoutParams
centerVertical.addRule(RelativeLayout.CENTER_HORIZONTAL)
binding.tvOccupantName.layoutParams = centerHorizontal

Hope it helps!


Assume that txtPhone is the textview that we are trying to place it center in horizontal.

If you are using Java then use the following code,

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) txtPhone.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
txtPhone.setLayoutParams(layoutParams);

If you are using Kotlin then use the following code,

val layoutParams = txtPhone.getLayoutParams() as RelativeLayout.LayoutParams
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL)
txtPhone.setLayoutParams(layoutParams)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号