material-components-android icon indicating copy to clipboard operation
material-components-android copied to clipboard

[MaterialTextView] Set layout_gravity programmatically

Open caiogrc opened this issue 5 years ago • 2 comments

I can set at XML level the attribute layout_gravity to a MaterialTextView so I can put it centered in a place. I'm trying to do that programmatically but am unable to.

I would like a way to set the layout_gravity programmatically.

I have tryied declarign a LinearLayout.LayoutParams instead of a ViewGroup.LayoutParams because LinearLayout params do has an atribute gravity. I have tryied put the "gravity" on the parent (MaterialCardView) but didn't work either.

image The rounded ones were added programmatically, the squared ones were added at XML.

image XML example of using layout_gravity.

caiogrc avatar Apr 17 '21 20:04 caiogrc

Have you tried setting text alignment instead? https://developer.android.com/reference/android/view/View#setTextAlignment(int)

Also, try setting the android:layout_width of the text view to match the parent, it's possible because it's wrap_content the layout_gravity is not showing as you expect in the layout. Personally, I prefer setting the width to match_parent and using setTextAlignment instead of layout_gravity.

msasikanth avatar May 07 '21 18:05 msasikanth

MaterialCardView is a FrameLayout. So you should probably use FrameLayout. LayoutParams in your case.

Anyhow it doesn't seems a MaterialLibrary issue. Close this for now.

drchen avatar Jun 18 '21 19:06 drchen