2015-09-19 94 views
13

enter image description hereAndroid小吃店TextAlignment中心

如何將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(); 

回答

12
tv.setGravity(Gravity.CENTER_HORIZONTAL); 

編輯

Snackbar出現在Support庫V23更改,因此正確答案是現在:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ 
    tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); 
} else { 
    tv.setGravity(Gravity.CENTER_HORIZONTAL); 
} 
+1

我不能得到只用setGravity所需的效果(即沒有setTextAlignment,這是API 17)。我正在使用支持庫23.2.0 ... –

+2

@kevinze我只是通過setTextAlignment和沒有setGravity來實現它,在API 23上支持23.3.0。 – hata

5

這一套做的我的招數:

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) { 
      v.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); 
     } 
    tv.setGravity(Gravity.CENTER_HORIZONTAL); 
} 
22

試試這個:

// 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(); 
-1

嘗試下面的代碼是在中心集小吃吧文字工作:

Snackbar snackbar = Snackbar.make(main_layout, "This is snack", Snackbar.LENGTH_LONG); 
    View snackbarView = snackbar.getView(); 
    Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView(); 
    layout.setGravity(Gravity.CENTER); 
    TextView mTextView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text); 
    mTextView.setGravity(Gravity.CENTER_HORIZONTAL); 
    mTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); 
    snackbar.show(); 
0

以上條件setTextAlignment() OR setGravity()解決方案沒有對API爲我工作26

適用於防彈文字:

  1. 始終應用setGravity()
  2. 應用setTextAlignment()爲API> = 17

代碼:

... 

sbTextView.setGravity(Gravity.CENTER_HORIZONTAL); 

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { 
    sbTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); 
} 

...