安卓自定義對話框(位置和大小)

安卓自定義對話框(位置和大小)


		//自定義對話框
		private void showCustomDialog(String msgStr){
			try {
				//使用AlterDialog
				LinearLayout view = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.dlg_layout, null);
				final TextView msg = (TextView) view.findViewById(R.id.dlg_msg);
				final TextView cancel = (TextView) view.findViewById(R.id.dlg_cancel);
				final TextView confirm = (TextView) view.findViewById(R.id.dlg_confirm);

				msg.setText(msgStr);
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				final AlertDialog dialog = builder.create();
				dialog.setCancelable(false);
				dialog.setCanceledOnTouchOutside(false);
				dialog.show();

				Window window = dialog.getWindow();
				//設置顯示位置
				WindowManager.LayoutParams lp = window.getAttributes();
				//不設置lp.width 和lp.height,對話框大小由佈局決定
//				lp.width = 525; //大小
//				lp.height =330;

				//自定義位置
				lp.x = 30; 
				lp.y = 30;
				lp.gravity = Gravity.LEFT | Gravity.TOP;//不設置這個時,lp.x和lp.y無效
				
			    //window.setGravity(Gravity.CENTER);//居中顯示
				window.setAttributes(lp);
				window.setContentView(view);


				final Dialog dialog2 = dialog;
				cancel.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						try {
							if(dialog2 != null){
								dialog2.dismiss();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				confirm.setOnClickListener(new View.OnClickListener() {
					public void onClick(View arg0) {
						try{
							Toast.makeText(DownLoadActivity.this, "確認", Toast.LENGTH_SHORT).show();
							if(dialog2 != null){
								dialog2.dismiss();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
lp.x的英文註釋:		
X position for this window. With the default gravity it is ignored. When using Gravity.LEFT or Gravity.START or Gravity.RIGHT or Gravity.END it provides an offset from the given edge
由With the default gravity it is ignored可知,當使用對話框默認的Gravity時,lp.x和lp.y設置了也無效。		
注意:lp.x與lp.y表示相對於原始位置的偏移.
          當參數值包含Gravity.LEFT時,對話框出現在左邊,所以lp.x就表示相對左邊的偏移,負值忽略.
          當參數值包含Gravity.RIGHT時,對話框出現在右邊,所以lp.x就表示相對右邊的偏移,負值忽略.
          當參數值包含Gravity.TOP時,對話框出現在上邊,所以lp.y就表示相對上邊的偏移,負值忽略.
          當參數值包含Gravity.BOTTOM時,對話框出現在下邊,所以lp.y就表示相對下邊的偏移,負值忽略.
          當參數值包含Gravity.CENTER_HORIZONTAL時,對話框水平居中,所以lp.x就表示在水平居中的位置移動lp.x像素,正值向右移動,負值向左移動.
          當參數值包含Gravity.CENTER_VERTICAL時,對話框垂直居中,所以lp.y就表示在垂直居中的位置移動lp.y像素,正值向右移動,負值向左移動.
          gravity的默認值爲Gravity.CENTER,即Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL.
          
        

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章