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,
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();
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()
}
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();
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();
Toast toast = Toast.makeText(this, "Message", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();