4

How do I set a TextView's layout_gravity by code?

I tried with layoutparams without any good result.

new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, Gravity.LEFT | Gravity.CENTER_VERTICAL); 

After using this my text just stays where it is standardly, at the top left corner. Neither the width: FILL_PARENT or the gravity codes do anything.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222

5 Answers5

13
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL)
Radu
  • 2,076
  • 2
  • 20
  • 40
Dawid Sajdak
  • 3,064
  • 2
  • 23
  • 37
2

u can use gravity in code by using below code :

    Button button = (Button) findViewById(R.id.MyButtonId);
    // need to cast to LinearLayout.LayoutParams to access the gravity field
    LayoutParams params = (LayoutParams)button.getLayoutParams(); 
    params.gravity = Gravity.BOTTOM;
    button.setLayoutParams(params);
Nikhil Lamba
  • 593
  • 1
  • 6
  • 17
1

Android set the gravity for a TextView programmatically Have you seen this response ?

TextView tv  = (TextView) findViewById(R.layout.text_view);   
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
Community
  • 1
  • 1
Skies
  • 407
  • 2
  • 6
0
 layout = (LinearLayout) findViewById(R.id.vendor_detail_lay);
    LinearLayout linearLayout = new LinearLayout(getApplicationContext());
    linearLayout.setOrientation(0);
    txtveiw = new TextView(NewVendorDetailActivity.this);
    txtveiw.setLayoutParams(Gravity.LEFT | Gravity.CENTER_VERTICAL);
    txtveiw.setId(itemId);
    txtveiw.setText(cursor.getString(cursor.getColumnIndex(DataBaseHelper.KEYNAME)));

    linearLayout.addView(txtveiw);
    layout.addView(linearLayout);
Android
  • 1,417
  • 9
  • 11
-1

best solution for keeping existing layout params:

  • You need to use LayoutParams of the parent layout (hence layout_gravity)
  • for example if parent is FrameLayout do:

    FrameLayout.LayoutParams layoutParams = 
        new FrameLayout.LayoutParams(textView.getLayoutParams());
    layoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT;
    textView.setLayoutParams(layoutParams);
    
mtyy
  • 1
  • 2