提示框的优化之自定义Toast组件之(三)Toast组件优化

时间:2023-12-15 00:00:02

开发步骤:

  • 在toast_customer.xml文件中添加一个图片组件对象显示提示图片
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout ......> <ImageView android:id="@+id/toastIcon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center_vertical"/> ...... </LinearLayout>
  • 在LoginActivity.java类中的自定义Toast调用方法中添加对图片组件的设置
 public class LoginActivity extends AppCompatActivity {

     ........

     private void showCustomerToast(final int icon, final String message){
LayoutInflater inflater=getLayoutInflater();
View layout=inflater.inflate(R.layout.toast_customer, (ViewGroup) findViewById(R.id.toast_layout_root));
...... //图片组件的设置
ImageView toastIcon=(ImageView)layout.findViewById(R.id.toastIcon);
toastIcon.setBackgroundResource(icon); ...... Toast toast=new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
......
}
  • 调用该方法
 public class LoginActivity extends AppCompatActivity {
......
private class ViewOcl implements View.OnClickListener{
public void onClick (View v){
......
if (login_flag) {
showCustomerToast(android.R.drawable.ic_menu_call,"欢迎登录," + account);
......
}
else {
showCustomerToast(android.R.drawable.ic_delete,"账号或密码错误");
}
break;
......
}
}
......
}

运行:

提示框的优化之自定义Toast组件之(三)Toast组件优化

提示框的优化之自定义Toast组件之(三)Toast组件优化

接下来,同理,把自定义方法showCustomerToast()放入Register_Activity.java中,在Checkform()中调用,修改注册页面的警告样式:

 public class Register_Activity extends AppCompatActivity {
......
private boolean checkform() {
if (this.txtRegAccount.getText().toString() == null || this.txtRegAccount.getText().toString().length() == 0) { //Toast.makeText(getApplicationContext(), "警告:注册账号不能为空", Toast.LENGTH_LONG).show();
showCustomerToast(android.R.drawable.ic_delete, "警告:注册账号不能为空");
return false;
}
if (this.txtRegPassword.getText().toString() == null || this.txtRegPassword.getText().toString().length() == 0) {
//Toast.makeText(getApplicationContext(), "警告:注册密码不能为空", Toast.LENGTH_LONG).show();
showCustomerToast(android.R.drawable.ic_delete,"警告:注册密码不能为空");
return false;
}
if (!(this.txtRegPassword.getText().toString()).equals((this.txtReRegPassword.getText().toString()))) {
//Toast.makeText(getApplicationContext(), "警告:两次密码不一致", Toast.LENGTH_LONG).show();
showCustomerToast(android.R.drawable.ic_delete,"警告:两次密码不一致");
return false;
}
return true;
}
......
}

运行:

提示框的优化之自定义Toast组件之(三)Toast组件优化提示框的优化之自定义Toast组件之(三)Toast组件优化提示框的优化之自定义Toast组件之(三)Toast组件优化