Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Snackbar TextAlignment in Center

Tags:

android

enter image description here

How to change the Snackbar text alignment to center ? bellow code is not working

Snackbar snack = Snackbar.make(findViewById(android.R.id.content), intent.getStringExtra(KEY_ERROR_MESSAGE), Snackbar.LENGTH_LONG);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextColor(ContextCompat.getColor(LoginActivity.this, R.color.red_EC1C24));
tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
snack.show();
like image 744
Chathura Wijesinghe Avatar asked Sep 19 '15 12:09

Chathura Wijesinghe


People also ask

How do I use snackBar?

This example demonstrates how do I use snackBar in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


3 Answers

tv.setGravity(Gravity.CENTER_HORIZONTAL); 

EDIT

The appearance of Snackbar was changed in Support library v23 so the correct answer now is:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){     tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); } else {     tv.setGravity(Gravity.CENTER_HORIZONTAL); } 
like image 81
DmitryArc Avatar answered Sep 18 '22 12:09

DmitryArc


Try this:

// make snackbar Snackbar mSnackbar = Snackbar.make(view, R.string.intro_snackbar, Snackbar.LENGTH_LONG); // get snackbar view View mView = mSnackbar.getView(); // get textview inside snackbar view TextView mTextView = (TextView) mView.findViewById(android.support.design.R.id.snackbar_text); // set text to center if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)     mTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); else     mTextView.setGravity(Gravity.CENTER_HORIZONTAL); // show the snackbar mSnackbar.show(); 
like image 27
ashubuntu Avatar answered Sep 20 '22 12:09

ashubuntu


The above conditional setTextAlignment() OR setGravity() solution didn't work for me.

For bulletproof centered text:

  1. Always apply setGravity()
  2. Apply setTextAlignment() for API >= 17

And note the support library change in AndroidX. If using AndroidX, lookup the TextView by com.google.android.material.R.id.snackbar_text instead of android.support.design.R.id.snackbar_text.

Code:

TextView sbTextView = (TextView) findViewById(com.google.android.material.R.id.snackbar_text);

sbTextView.setGravity(Gravity.CENTER_HORIZONTAL);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    sbTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
}
like image 31
Maksim Ivanov Avatar answered Sep 18 '22 12:09

Maksim Ivanov