Center text in a toast in Android

后端 未结 11 1399
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 01:58

I was wondering if there was a way to display all text in a toast to be centered. For instance, I have a toast that has 2 lines of text in it. For purely aesthetic reasons,

相关标签:
11条回答
  • 2020-12-13 02:17

    Adapted from another answer:

    Toast toast = Toast.makeText(this, "Centered\nmessage", Toast.LENGTH_SHORT);
    TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
    if( v != null) v.setGravity(Gravity.CENTER);
    toast.show();
    
    0 讨论(0)
  • 2020-12-13 02:19

    In kotlin:

    fun makeToast(context: Context, resId: Int) {
        val toast = Toast.makeText(context, resId, Toast.LENGTH_SHORT)
        val view = toast.view.findViewById<TextView>(android.R.id.message)
        view?.let {
            view.gravity = Gravity.CENTER
        }
        toast.show()
    }
    
    0 讨论(0)
  • 2020-12-13 02:22

    Not saing that findViewById(android.R.id.message) is wrong, but just in case there are (future?) implementation differences I myself used a bit differen approach:

    void centerText(View view) {
        if( view instanceof TextView){
            ((TextView) view).setGravity(Gravity.CENTER);
        }else if( view instanceof ViewGroup){
            ViewGroup group = (ViewGroup) view;
            int n = group.getChildCount();
            for( int i = 0; i<n; i++ ){
                centerText(group.getChildAt(i));
            }
        }
    }
    

    and then:

    Toast t = Toast.makeText(context, msg,Toast.LENGTH_SHORT);
    centerText(t.getView());
    t.show();
    
    0 讨论(0)
  • 2020-12-13 02:22

    This variation is with using LinearLayout. :)

    Toast SampleToast = Toast.makeText(this, "This is the example of centered text.\nIt is multiline text.", Toast.LENGTH_SHORT);
    LinearLayout OurLayout = (LinearLayout) SampleToast.getView();
    
    if (OurLayout.getChildCount() > 0) 
    {
    TextView SampleView = (TextView) OurLayout.getChildAt(0);
    SampleView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
    }
    
    SampleToast.show();
    
    0 讨论(0)
  • 2020-12-13 02:25
    Toast toast = Toast.makeText(this, "Message", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();
    
    0 讨论(0)
提交回复
热议问题