Center text in a toast in Android

后端 未结 11 1418
没有蜡笔的小新
没有蜡笔的小新 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: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

    and then:

    Toast t = Toast.makeText(context, msg,Toast.LENGTH_SHORT);
    centerText(t.getView());
    t.show();
    

提交回复
热议问题