Android Snackbar TextAlignment in Center

前端 未结 6 1882
误落风尘
误落风尘 2021-02-18 13:30

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

Snackbar snack = Snackbar.make(findViewById(android.R.id.content), in         


        
6条回答
  •  广开言路
    2021-02-18 14:16

    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);
    }
    

提交回复
热议问题