要在不使用XML的情况下创建自定义Toast,可以通过以下步骤:
public class CustomToast {
public static Toast makeText(Context context, CharSequence text, int duration) {
Toast toast = Toast.makeText(context, text, duration);
// Create a new layout for the custom toast
LinearLayout layout = new LinearLayout(context);
layout.setBackgroundColor(Color.BLACK);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setPadding(16, 16, 16, 16);
// Create a new TextView for the toast message
TextView textView = new TextView(context);
textView.setText(text);
textView.setTextColor(Color.WHITE);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
textView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
// Add the TextView to the layout
layout.addView(textView);
// Set the custom layout for the toast
toast.setView(layout);
return toast;
}
}
CustomToast.makeText(getApplicationContext(), "This is a custom toast", Toast.LENGTH_SHORT).show();
这样就可以在不使用XML的情况下创建自定义Toast了。在上面的示例中,我们创建了一个自定义的LinearLayout作为Toast的布局,并在其中添加了一个TextView来显示Toast的文本内容。你可以根据自己的需求修改布局和样式。