下面提供一些比較進階的問題
Q1:如何讓Dialog不會被back鍵 及 觸碰空白處取消
A:(參考)
public class CantBeDismissDialog extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//AlertDialog builder物件
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//設定AlertDialog內容
builder.setTitle("系統提示")
.setMessage("請問你是男生還是女生?")
.setPositiveButton("Boy", null)
.setNegativeButton("Girl", null)
.setCancelable(false); //設定back鍵無法dismiss dialog
//建立AlertDialog
AlertDialog alert = builder.create();
//顯示AlertDialog
alert.show();
//註冊key event listener
alert.setOnKeyListener(new OnKeyListener()
{
@Override
public boolean onKey(DialogInterface dialog, int code, KeyEvent event) {
if(code==KeyEvent.KEYCODE_SEARCH) //如果按下Search鈕
return true;
else
return false;
}
});
}
}
Q2:如何自定義AlertDialog & 如何在AlertDialog內放置元件
A:參考 http://cookiesp.pixnet.net/blog/post/77342445
Q3:如何產生橫的AlertDialog
A:參考
//產生dialog
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Test Dialog")
.setMessage("This should expand to the full width")
.show();
//Grab the window of the dialog, and change the width
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = dialog.getWindow();
lp.copyFrom(window.getAttributes());
//This makes the dialog take up the full width
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(lp);
Q4:如何自定AlertDialog的位置
A:
AlertDialog dlg = new AlertDialog.Builder(context).create();
LayoutInflater flater = LayoutInflater.from(context);
View view = flater.inflate(R.layout.mode_tv_layout2_gridview_dialog, null);
dlg.setView(view);
dlg.show();
方法一
Window window = dlg.getWindow();
window.setGravity(Gravity.BOTTOM);//BOTTOM為底部 可自選
方法二
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = dlg.getWindow();
lp = window.getAttributes();
lp.alpha = 0.5f;//透明度
lp.y = 100;//高度
window.setAttributes(lp);
Q5: