Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 自訂登入對話框:布局、Dialog 與背景執行緒的完整實作

本篇實作一個自訂樣式的登入視窗:用 AlertDialog 承載自訂布局,加入帳號密碼輸入與錯誤提示,按下登入後顯示等待進度視窗,再由 Handler 在背景完成與伺服器的 socket 通訊。

登入視窗布局 login_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="https://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical">

  <TextView
      android:id="@+id/txt_loginerror"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:layout_marginLeft="20dip"
      android:layout_marginRight="20dip"
      android:textColor="#ff0000"
      android:text="輸入的賬號和密碼不正確"
      android:gravity="left"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:visibility="invisible"
  />

  <TextView
      android:id="@+id/username"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:layout_marginLeft="20dip"
      android:layout_marginRight="20dip"
      android:text="賬號"
      android:gravity="left"
      android:textAppearance="?android:attr/textAppearanceMedium"
  />

  <EditText
      android:id="@+id/txt_username"
      android:layout_height="wrap_content"
      android:layout_width="fill_parent"
      android:layout_marginLeft="20dip"
      android:layout_marginRight="20dip"
      android:autoText="false"
      android:capitalize="none"
      android:gravity="fill_horizontal"
      android:textAppearance="?android:attr/textAppearanceMedium"
  />

  <TextView
      android:id="@+id/password"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:layout_marginLeft="20dip"
      android:layout_marginRight="20dip"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:text="密碼"
      android:gravity="left"
  />

  <EditText
      android:id="@+id/txt_password"
      android:layout_height="wrap_content"
      android:layout_width="fill_parent"
      android:layout_marginLeft="20dip"
      android:layout_marginRight="20dip"
      android:autoText="false"
      android:capitalize="none"
      android:gravity="fill_horizontal"
      android:textAppearance="?android:attr/textAppearanceMedium"
  />

  <TextView
      android:id="@+id/txt_toregister"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:layout_marginLeft="20dip"
      android:layout_marginRight="20dip"
      android:textColor="#2200C1"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:text="沒有賬號?快速注冊"
      android:gravity="left"
  />

</LinearLayout>

建立對話框與登入邏輯

private void CreateLoginAlert()
{
    LayoutInflater factory = LayoutInflater.from(LoginActivity.this);
    //得到自定義對話框
    View DialogView = factory.inflate(R.layout.login_dialog, null);

    AlertDialog.Builder ad = new AlertDialog.Builder(this);
    ad.setTitle("賬號登陸");
    ad.setView(DialogView);
    adi = ad.create();

    adi.setButton("登錄", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            username = (EditText)adi.findViewById(R.id.txt_username);
            password = (EditText)adi.findViewById(R.id.txt_password);
            loginerror = (TextView)adi.findViewById(R.id.txt_loginerror);

            m_Dilog = ProgressDialog.show(LoginActivity.this, "請等待...", "正在為你登陸...", true);
            mRedrawHandler.sleep(100);
        }
    });

    adi.setButton2("取消", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
        }
    });
    adi.show();
}

private RefreshHandler mRedrawHandler = new RefreshHandler();
class RefreshHandler extends Handler{

    @Override
    public void handleMessage(Message msg) {
        try {
            socket = new Socket("113.250.155.194", 9999);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(username.getText().length() == 0)
        {
        adi.show();
        loginerror.setText("賬號不能為空!");
        loginerror.setVisibility(loginerror.VISIBLE);
        }else if(password.getText().length() == 0){
        adi.show();
        loginerror.setText("密碼不能為空!");
        loginerror.setVisibility(loginerror.VISIBLE);
        }else{
        UserModel users = new UserModel();
        users.setUserName(username.getText().toString());
        users.setUserPass(password.getText().toString());
        users.setUserState(1);
              users.setGuanliyuan(0);
        out.println("login&" + UserModel.userToString(users));
            out.flush();

            String line;
        try {
            line = in.readLine();
            System.out.println("登錄窗口從服務器收到的消息為:" + line);
            if (line.startsWith("LOGINOK")) {
                UserModel user = UserModel.getUserByString(line);
                 out.println("updateList&" + UserModel.userToString(user));
                 out.flush();
                 Toast.makeText(LoginActivity.this, "登陸成功", Toast.LENGTH_SHORT).show();
            }else
                if (line.equals("ERROR")) {
                 Toast.makeText(LoginActivity.this, "登陸失敗", Toast.LENGTH_SHORT).show();
                 adi.show();
                 adi.findViewById(R.id.txt_loginerror).setVisibility(View.VISIBLE);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            m_Dilog.dismiss();
        }
        super.handleMessage(msg);
    }

    public void sleep(long delayMillis)
    {
        this.removeMessages(0);
        sendMessageDelayed(obtainMessage(0), delayMillis);
    }
}

實作要點

自訂對話框的關鍵是 LayoutInflater.from(...).inflate() 把 XML 變成 View,再交給 AlertDialog.Builder.setView()。要注意控制項必須透過 adi.findViewById 而非 Activity 的 findViewById 取得,因為它們屬於對話框的視圖樹。

耗時的 socket 連線透過 sendMessageDelayed 延後 100 毫秒派送,讓 ProgressDialog 有時間先顯示出來,再由 Handler 的 handleMessage 執行網路作業,避免在 UI 執行緒上做阻塞式 IO。錯誤提示 TextView 在布局中預設 visibility="invisible",驗證失敗時才切換成 VISIBLE,紅字呈現。

實務上有兩點建議改進:一是 socket 連線與讀寫應放在背景 Thread 或 AsyncTask 中並確實關閉,目前範例未關閉連線會造成資源洩漏;二是登入憑證以明文自串接字串傳輸並不安全,正式環境應改用 HTTPS 並避免直接回傳密碼欄位。

Copyright © Linux教程網 All Rights Reserved