开发步骤:
- 在toast_customer.xml文件中添加一个图片组件对象显示提示图片
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout ......> 3 4 <ImageView android:id="@+id/toastIcon" 5 android:layout_width="24dp" 6 android:layout_height="24dp" 7 android:layout_gravity="center_vertical"/> 8 9 ...... 10 11 </LinearLayout>
- 在LoginActivity.java类中的自定义Toast调用方法中添加对图片组件的设置
1 public class LoginActivity extends AppCompatActivity { 2 3 ........ 4 5 private void showCustomerToast(final int icon, final String message){ 6 LayoutInflater inflater=getLayoutInflater(); 7 View layout=inflater.inflate(R.layout.toast_customer, (ViewGroup) findViewById(R.id.toast_layout_root)); 8 ...... 9 10 //图片组件的设置 11 ImageView toastIcon=(ImageView)layout.findViewById(R.id.toastIcon); 12 toastIcon.setBackgroundResource(icon); 13 14 ...... 15 16 Toast toast=new Toast(getApplicationContext()); 17 toast.setDuration(Toast.LENGTH_LONG); 18 toast.setView(layout); 19 toast.show(); 20 } 21 ...... 22 }
- 调用该方法
1 public class LoginActivity extends AppCompatActivity { 2 ...... 3 private class ViewOcl implements View.OnClickListener{ 4 public void onClick (View v){ 5 ...... 6 if (login_flag) { 7 showCustomerToast(android.R.drawable.ic_menu_call,"欢迎登录," + account); 8 ...... 9 } 10 else { 11 showCustomerToast(android.R.drawable.ic_delete,"账号或密码错误"); 12 } 13 break; 14 ...... 15 } 16 } 17 ...... 18 }
运行:
接下来,同理,把自定义方法showCustomerToast()放入Register_Activity.java中,在Checkform()中调用,修改注册页面的警告样式:
1 public class Register_Activity extends AppCompatActivity { 2 ...... 3 private boolean checkform() { 4 if (this.txtRegAccount.getText().toString() == null || this.txtRegAccount.getText().toString().length() == 0) { 5 6 //Toast.makeText(getApplicationContext(), "警告:注册账号不能为空", Toast.LENGTH_LONG).show(); 7 showCustomerToast(android.R.drawable.ic_delete, "警告:注册账号不能为空"); 8 return false; 9 } 10 if (this.txtRegPassword.getText().toString() == null || this.txtRegPassword.getText().toString().length() == 0) { 11 //Toast.makeText(getApplicationContext(), "警告:注册密码不能为空", Toast.LENGTH_LONG).show(); 12 showCustomerToast(android.R.drawable.ic_delete,"警告:注册密码不能为空"); 13 return false; 14 } 15 if (!(this.txtRegPassword.getText().toString()).equals((this.txtReRegPassword.getText().toString()))) { 16 //Toast.makeText(getApplicationContext(), "警告:两次密码不一致", Toast.LENGTH_LONG).show(); 17 showCustomerToast(android.R.drawable.ic_delete,"警告:两次密码不一致"); 18 return false; 19 } 20 return true; 21 } 22 ...... 23 }
运行: