2016-12-23 112 views
0

我試圖以像素爲單位獲取AlertDialog的寬度,並且還動態設置其寬度。獲取AlertDialog的寬度(以像素爲單位)或dp

getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); 
int width = displaymetrics.widthPixels; 

WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 
lp.copyFrom(dialog.getWindow().getAttributes()); 
lp.width = width; 
lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 
lp.gravity = Gravity.CENTER; 

dialog.getWindow().setAttributes(lp); 

上述代碼對我無效。另外,我也跟着其他代碼,如here,但沒有任何幫助。

如何獲取並設置寬度爲AlertDialog像素或dp?

+1

來自鏈接解決方案,您嘗試過哪些代碼? –

回答

1

你只能得到widht和觀點的高度, 因此,如果其自定義對話框,取其根視圖親切效仿

RelativeLayout rl = (RelativeLayout) dialog.findViewById(R.id.root_relative_layout); 

這裏相對佈局是父視圖和組件都在上面。

我們得到高度和寬度做到這一點: -

int width = rl.getWidth(); 
int height = rl.getHeight(); 

設置widht和高度做這個

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setView(layout); 
    builder.setTitle("Title"); 
    alertDialog = builder.create(); 
    alertDialog.getWindow().setLayout(600, 400); //Controlling width and height. 
    alertDialog.show(); 

OR

WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 

lp.copyFrom(alertDialog.getWindow().getAttributes()); 
lp.width = 150; 
lp.height = 500; 
lp.x=-170; 
lp.y=100; 
alertDialog.getWindow().setAttributes(lp); 
0

替換下面的代碼:

dialog.getWindow().setLayout(getResources().getDimensionPixelSize(R.dimen.layout_height_400dp), WindowManager.LayoutParams.MATCH_PARENT); 
相關問題