Reputation: 100368
In xml you can do the following:
<TextView
...
android:layout_centerHorizontal="true"
...
/>
How would I, when I have the instance of TextView
, do this programmatically?
Upvotes: 47
Views: 34363
Reputation: 674
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!
Upvotes: 2
Reputation: 1
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)
Upvotes: 0
Reputation: 6862
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.
Upvotes: 28
Reputation: 24233
You should use the addRule
method of the RelativeLayout.LayoutParams
class.
layoutparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
mTextView.setLayoutParams(layoutParams);
Upvotes: 113