Toast
- Toast是一个消息提示组件
- 设置显示的位置
- 自定义显示内容(添加一个图片)
- 简单封装
ToastActivity
public class ToastActivity extends AppCompatActivity {
private Button mBtnToast1, mBtnToast2, mBtnToast3, mBtnToast4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toast);
mBtnToast1 = findViewById(R.id.btn_toast_1);
mBtnToast2 = findViewById(R.id.btn_toast_2);
mBtnToast3 = findViewById(R.id.btn_toast_3);
mBtnToast4 = findViewById(R.id.btn_toast_4);
OnClick onClick = new OnClick();
mBtnToast1.setOnClickListener(onClick);
mBtnToast2.setOnClickListener(onClick);
mBtnToast3.setOnClickListener(onClick);
mBtnToast4.setOnClickListener(onClick);
}
class OnClick implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_toast_1:
Toast.makeText(ToastActivity.this, "Toast", Toast.LENGTH_LONG).show();
break;
case R.id.btn_toast_2:
Toast toastCenter = Toast.makeText(ToastActivity.this, "居中Toast", Toast.LENGTH_LONG);
toastCenter.setGravity(Gravity.CENTER, 0, 0);
toastCenter.show();
break;
case R.id.btn_toast_3:
Toast toastCustom = new Toast(getApplicationContext());
LayoutInflater inflater = LayoutInflater.from(ToastActivity.this);
View view = inflater.inflate(R.layout.layout_toast, null);
ImageView imageView = view.findViewById(R.id.iv_toast);
TextView textView = view.findViewById(R.id.tv_toast);
imageView.setImageResource(R.drawable.arrowdown);
textView.setText("自定义Toast");
toastCustom.setView(view);
toastCustom.show();
toastCustom.setDuration(Toast.LENGTH_LONG);
break;
case R.id.btn_toast_4:
ToastUtil.showMessage(getApplicationContext(), "包装过的msg");
break;
}
}
}
}
自定义ToastView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#99000000"
android:gravity="center"
>
<LinearLayout
android:layout_width="200dp"
android:layout_height="200dp"
android:orientation="vertical"
android:gravity="center"
>
<ImageView
android:id="@+id/iv_toast"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitCenter"/>
<TextView
android:id="@+id/tv_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="@color/colorWhite"
android:layout_marginTop="20dp"/>
</LinearLayout>
</LinearLayout>
封装Toast工具类
public class ToastUtil {
public static Toast mToast;
public static void showMessage(Context context, String msg) {
if (mToast == null) {
mToast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
} else {
mToast.setText(msg);
}
mToast.show();
}
}