爲什麼叫Toast?我擦 ,爲什麼一定要獨立一個類似對話框的東東呢?
查了下,Toast是吐司,一種美國人早上插到烤麪包機裏考了再喫的麪包!遂明白,大概爲這個組件命名的人形象的給這個組件賦予了這個名字。Toast就像是那種麪包一樣一下子跳出來。那爲啥不是一種Dialog呢? 誒 ,學習了下: DIY效果由淺入深
1.默認普通效果的Toast
效果:
代碼:
Toast.makeText(getApplicationContext(), "這是一個普通的toast", Toast.LENGTH_SHORT).show();
2.自定義位置的Toast
效果:
代碼:
Toast toast=Toast.makeText(getApplicationContext(), "這是一個自定義位置的Toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,50, 100);
toast.show();
3.自定義帶圖片的Toast
效果:
代碼:
Toast toast=Toast.makeText(getApplicationContext(), "自定義圖片的Toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView imageCodeProject = new ImageView(getApplicationContext());
imageCodeProject.setImageResource(R.drawable.ic_launcher);
toastView.addView(imageCodeProject, 0);
toast.show();
4.完全自定義Toast
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom,(ViewGroup) findViewById(R.id.llToast));
ImageView image = (ImageView) layout
.findViewById(R.id.tvImageToast);
image.setImageResource(R.drawable.icon);
TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
title.setText("Attention");
TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
text.setText("完全自定義Toast");
toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();