3

How to align message textview to the center Horizontally in snackbar in android?

Sudhir Sinha
  • 693
  • 9
  • 18
  • 3
    possible duplicate of [How do I center text horizontally and vertically in a TextView in Android?](http://stackoverflow.com/questions/432037/how-do-i-center-text-horizontally-and-vertically-in-a-textview-in-android) or http://stackoverflow.com/questions/32668217/android-snackbar-textalignment-in-center – string.Empty Sep 21 '15 at 11:30
  • 1
    This is not duplicate. This question regards Snackbar or CoordinatorLayout in android. Sorry it is not duplicate question. Thanks – Omar Faroque Anik Sep 24 '15 at 21:07
  • Snackbar text-message is of AppCompatTextview type which can be aligned desirously as it happened with normal textview. AppCompatTextView tv = (AppCompatTextView) view.findViewById(android.support.design.R.id.snackbar_text); tv.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL); – Sudhir Sinha Sep 25 '15 at 07:13
  • This is not a duplicate. – Louth Nov 26 '15 at 03:02

2 Answers2

6

Below is a sample, for making the Snackbar Text center horizontal

Snackbar snackbar = Snackbar.make(findViewById(R.id.coordinatorLayout), "Hello", Snackbar.LENGTH_SHORT);
snackbar.show();
View view = snackbar.getView();
TextView txtv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
txtv.setGravity(Gravity.CENTER_HORIZONTAL);

If you are using androidX

then replace the textview id com.google.android.material.R.id.snackbar_text

Nigam Patro
  • 2,760
  • 1
  • 18
  • 33
  • 2
    For AndroidX, the correct view id for the TextView is ```com.google.android.material.R.id.snackbar_text``` – Awsom3D Apr 13 '20 at 22:18
1

Try to set both textAlignment and Gravity to the Gravity.CENTER_HORIZONTAL

snackTextView.setGravity(Gravity.CENTER_HORIZONTAL);   
snackTextView.setTextAlignment(Gravity.CENTER_HORIZONTAL);
Jemo Mgebrishvili
  • 5,187
  • 7
  • 38
  • 63