中心的Android Snackbar TextAlignment

Cha*_*ghe 20 android

在此输入图像描述

如何将Snackbar文本对齐更改为居中?波纹管代码不起作用

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();
Run Code Online (Sandbox Code Playgroud)

ash*_*ntu 31

试试这个:

// 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();
Run Code Online (Sandbox Code Playgroud)


Dmi*_*Arc 24

tv.setGravity(Gravity.CENTER_HORIZONTAL);
Run Code Online (Sandbox Code Playgroud)

编辑

库v23中的外观Snackbar已经改变,Support所以现在正确的答案是:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
    tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
} else {
    tv.setGravity(Gravity.CENTER_HORIZONTAL);
}
Run Code Online (Sandbox Code Playgroud)

  • @kevinze我只使用setTextAlignment并且没有setGravity,在API 23上支持23.3.0. (2认同)

Mak*_*nov 9

上述条件setTextAlignment() OR setGravity()解决方案对我不起作用。

对于防弹居中的文本:

  1. 始终适用 setGravity()
  2. 申请setTextAlignment()API >= 17

并注意AndroidX 中的支持库更改。如果使用 AndroidX,请通过com.google.android.material.R.id.snackbar_text而不是android.support.design.R.id.snackbar_text.

代码:

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);
}
Run Code Online (Sandbox Code Playgroud)


Tar*_*run 6

下面的代码对我有用:

TextView tv = (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);
}
Run Code Online (Sandbox Code Playgroud)