1

I need to set layout gravity for Textview which is inside Relative layout, I do this via xml but how to do it programmatically?

<Relativelayout>
    <Textview
     android:gravity="left"
     android:layout_gravity="center_vertical|right"/>
</Relativelayout>

I need to set gravity and layout_gravity programmatically.

ASN
  • 1,655
  • 4
  • 24
  • 52
dev_swat
  • 1,264
  • 1
  • 12
  • 26

5 Answers5

2

Try this

Use RelativeLayout.LayoutParams

Specifies how a view is positioned within a RelativeLayout. The relative layout containing the view uses the value of these layout parameters to determine where to position the view on the screen. If the view is not contained within a relative layout, these attributes are ignored.

Sample Code

TextView textView=findViewById(R.id.spn);
RelativeLayout.LayoutParams layoutParams =
                (RelativeLayout.LayoutParams)textView.getLayoutParams();    
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
textView.setLayoutParams(layoutParams);
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
1

Try this one:

  RelativeLayout relativeLayout=new RelativeLayout(this);
  TextView textView=new TextView(this);
  RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
  layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
  layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
  textView.setLayoutParams(layoutParams);
  relativeLayout.addView(textView);
Mahesh Vayak
  • 1,056
  • 12
  • 25
0

Create a layoutParams object, define your gravity there and set it to your textview.

0
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
    params.weight = 1.0f;
    params.gravity = Gravity.TOP;

button.setLayoutParams(params);

Replace LinearLayout.LayoutParamswith RelativeLayout.LayoutParams

DPE
  • 218
  • 5
  • 15
0
 Textview tx= new Textview(this);
RelativeLayout.LayoutParams params = new Relative.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.center_vertical;

tx.setLayoutParams(params):

or another option check this link https://android--code.blogspot.com/2015/05/android-textview-layout-gravity.html

Addisalem
  • 108
  • 4