3

I have created 5 TextView programmatically, now i want to set few Parameters/Attributes of their such as Gravity, Layout_Gravity, etc.

I know we can set it in XML layout at Design-time:

android:gravity="center|center_horizontal|center_vertical"
android:layout_gravity="center|center_horizontal|center_vertical"

But, How can we set Gravity/Layout_Gravity kinds of Attributes programmatically?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295

2 Answers2

4

You can set the gravity of TextView programmatically using setGravity(int))

Probably you can set layout_gravity like this(I've not yet tested this) :

TextView can let its parent know about layout preferences using

setLayoutParams(ViewGroup.LayoutParams params)
LayoutParams params=new LayoutParams(this, attrSet);
tv.setLayoutParams(params);
Rahul Sharma
  • 2,867
  • 2
  • 27
  • 40
Suresh
  • 9,495
  • 14
  • 49
  • 63
  • 1
    Adding to what suresh has said i don't see a direct method to set layout_gravity programmatically. You could see android:layout_gravity doesn't have any direct java related methods in documentation where as android:gravity has one http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html – DeRagan Nov 29 '10 at 07:19
  • Layout gravity is for ViewGroup but TextView is not ViewGroup, is it right to set layout_gravity for it.? – Suresh Nov 29 '10 at 07:22
  • The textview might be inside a viewgroup. We do not have the layout posted here... Anyhow framelayout can accept gravity in layout params... You can check if that helps you. http://developer.android.com/reference/android/widget/FrameLayout.LayoutParams.html#FrameLayout.LayoutParams%28int,%20int,%20int%29 http://stackoverflow.com/questions/2945315/java-method-for-androidlayout-gravity – DeRagan Nov 29 '10 at 07:24
  • Probably you can use setLayoutParams(ViewGroup.LayoutParams params) to set the layout_gravity. – Suresh Nov 29 '10 at 07:25
  • 1
    Well that depends on the layout that is being used. LinearLayout and RelativeLayout cannot accept gravity to be passed on setLayoutParams where as FrameLayout can as per the docs http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#RelativeLayout.LayoutParams%28android.view.ViewGroup.LayoutParams%29 http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html#LinearLayout.LayoutParams%28int,%20int,%20float%29 – DeRagan Nov 29 '10 at 07:32
0

It's all in the docs. Look at the documentation for View, for example, under "XML Attributes". You'll see all XML attributes, and the corresponding method you'll need to call in code to get the same effect.

EboMike
  • 76,846
  • 14
  • 164
  • 167