Android Snackbar Textalignment In Center
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_ERR
Solution 1:
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);
}
Solution 2:
Try this:
// make snackbarSnackbarmSnackbar= Snackbar.make(view, R.string.intro_snackbar, Snackbar.LENGTH_LONG);
// get snackbar viewViewmView= mSnackbar.getView();
// get textview inside snackbar viewTextViewmTextView= (TextView) mView.findViewById(android.support.design.R.id.snackbar_text);
// set text to centerif (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();
Solution 3:
The above conditional setTextAlignment() OR setGravity()
solution didn't work for me.
For bulletproof centered text:
- Always apply
setGravity()
- 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:
TextViewsbTextView= (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);
}
Solution 4:
The code below does the trick for me:
TextViewtv= (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
if(tv!=null) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN)
tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
}
Solution 5:
Use "com.google.android.material" instead of "android.support.design.R" as it is no more supported after androidx migration.
FloatingActionButtonfab= findViewById(R.id.fab);
fab.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View view) {
SnackbarmSnackbar= Snackbar.make(view, R.string.copyright, Snackbar.LENGTH_SHORT);
ViewmView= mSnackbar.getView();
TextViewmTextView= (TextView) mView.findViewById(com.google.android.material.R.id.snackbar_text);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
mTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
else
mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
mSnackbar.show();
}
});
Post a Comment for "Android Snackbar Textalignment In Center"