LearningBasics
LearningBasics

Reputation: 680

Android:How do I center TextView horizontally in LinearLayout Programatically

I have a textview view whose width doesn't cover all the parent's width. I have used valueTV.setGravity(Gravity.CENTER_HORIZONTAL);

and it puts the text in center of textview. Now I want to take the whole textview in the center of the parent ( which apparently covers the whole scrren). How can it be done programatically. I want to align the textview to center.Basically I know a lot of questions have already been asked which are quite similar to this but not exactly the same as they didnot solve my problem.

Upvotes: 0

Views: 241

Answers (2)

LHA
LHA

Reputation: 9655

// Make sure textview width match parent
// Use param: ViewGroup.LayoutParams.MATCH_PARENT

LinearLayout.LayoutParams layoutParams = 
  new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

// Make sure text is center
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;

linearLayout.addView(valueTV, layoutParams);

Upvotes: 1

feilong
feilong

Reputation: 1582

Hmmm... Try this perhaps

TextView tv = findViewById(R.id.yourTextView);
LinearLayout.LayoutParams layoutParams = 
(LinearLayout.LayoutParams)tv.getLayoutParams();
 layoutParams.gravity = Gravity.CENTER_HORIZONTAL;

tv.setLayoutParams(layoutParams);

Upvotes: 0

Related Questions