Sunday, 2 November 2014

How to programatically center text horizontally using TextView

Use the gravity attribute of the TextView. Like this:
The method setTextHorizontally below changes the text and the attributes of the TextView to center it horizontally. It assumes the text is in your string resource file
private void setTextHorizontally(int textResId){
  TextView textView = (TextView).findViewById(R.id.myTextView);
  textView.setText(textResId);
  textView.setGravity(Gravity.CENTER_HORIZONTAL);
}