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();
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.
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); }
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();
The above conditional setTextAlignment() OR setGravity()
solution didn't work for me.
For bulletproof centered text:
setGravity()
setTextAlignment()
for API >= 17And 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With