How to install LAYOUTGRAVITY for TextView in Android?

How to set TextView layout_gravity by code?

I tried with layoutparams without a good result.

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

After that, my text remains where it is standard in the upper left corner. Neither the width: FILL_PARENT nor the gravity codes do anything.

+4
source share
5 answers
 FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL) 
+13
source

u can use gravity in code using the code below:

  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); 
+1
source
  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); 
0
source

Android set up gravity for TextView programmatically Have you seen this answer?

 TextView tv = (TextView) findViewById(R.layout.text_view); tv.setGravity(Gravity.CENTER | Gravity.BOTTOM); 
0
source

best solution to save existing layout options:

  • You need to use the LayoutParams of the parent layout (hence the layout )
  • for example, if the parent of a FrameLayout does:

     FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(textView.getLayoutParams()); layoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; textView.setLayoutParams(layoutParams); 
-1
source

Source: https://habr.com/ru/post/1412511/


All Articles