Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 Toast 組件優化(三):為提示框添加圖標

編輯:關於 Android 開發

Toast 是 Android 中最常用的輕量級提示方式。默認的 Toast 只能顯示純文字,樣式單調。本篇文章將延續自定義 Toast 的思路,在提示框中加入圖標,讓提示信息更加直觀生動。

開發步驟

第一步:在 toast_customer.xml 中添加一個 ImageView 組件,用於顯示提示圖片。

<?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 替換原本單調的系統提示,讓錯誤提示更加醒目:

public class Register_Activity extends AppCompatActivity {
    ......
    private boolean checkform() {
        if (this.txtRegAccount.getText().toString() == null || this.txtRegAccount.getText().toString().length() == 0) {
            showCustomerToast(android.R.drawable.ic_delete, "警告:注冊賬號不能為空");
            return false;
        }
        if (this.txtRegPassword.getText().toString() == null || this.txtRegPassword.getText().toString().length() == 0) {
            showCustomerToast(android.R.drawable.ic_delete,"警告:注冊密碼不能為空");
            return false;
        }
        if (!(this.txtRegPassword.getText().toString()).equals((this.txtReRegPassword.getText().toString()))) {
            showCustomerToast(android.R.drawable.ic_delete,"警告:兩次密碼不一致");
            return false;
        }
        return true;
    }
    ......
}

運行後可以看到,帶圖標的 Toast 提示效果明顯優於系統默認樣式,能夠給用戶更清晰的視覺反饋。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved