在使用AlertDialog功能之前,要先import AlertDialog的函式庫,如果有使用到其他元件也要import,像這裡也有用到EditText,所以也要import
import android.support.v7.app.AlertDialog; import android.widget.EditText;在onCreate(Bundle savedInstanceState)方法或自定義的方法內宣告AlertDialog
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); EditText editText = new EditText(MainActivity.this); builder.setTitle("Please enter your Student ID"); builder.setView(editText); //按到旁邊的空白處AlertDialog也不會消失 builder.setCancelable(false); //註冊AlertDialog的按鈕,按下去之後發生的事件 builder.setPositiveButton("OK", altDlgOnClkPosiBtnLis); builder.show(); } private DialogInterface.OnClickListener altDlgOnClkPosiBtnLis = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //如果EditText是空值,AlertDialog就必須一直出現,否則執行else的程式 if ("".equals(editText.getText().toString().trim())) { //讓AlertDialog一直出現,我的方法是先把原本的AlertDialog所佔的資源釋放掉,再重新宣告一次. dialog.dismiss(); builder = new AlertDialog.Builder(MainActivity.this); editText = new EditText(MainActivity.this); builder.setTitle("Please enter your Student ID"); builder.setView(editText); builder.setCancelable(false); builder.setPositiveButton("OK", altDlgOnClkPosiBtnLis); builder.show(); }else{ //To do something else. } } }
沒有留言:
張貼留言