2012-10-26 45 views
0

我在xml中有一個佈局,其屬性高度爲700dp,寬度爲300 dp。如何在代碼中更改此佈局的大小? 我嘗試這樣的事情,但我得到空指針:調整代碼中的佈局

setContentView(R.layout.log_in_dialog_view); 
view = findViewById(R.layout.log_in_dialog_view); 
lp = view.getLayoutParams(); 
lp.height = 200; 
lp.width = 200; 
view.setLayoutParams(lp); 

回答

0

我用的窗口管理器:

DisplayMetrics dm = new DisplayMetrics(); 
getWindowManager().getDefaultDisplay().getMetrics(dm); 

height = dm.heightPixels; 
width = dm.widthPixels; 
    WindowManager.LayoutParams WMLP = getWindow() 
      .getAttributes(); 
    WMLP.width = width-200; 
    WMLP.height = height-200; 
0

一旦你的視圖的引用,你可以這樣做:

ViewGroup.LayoutParameters lp = view.getLayoutParameters(); 
lp.height = . . .; 
lp.width = . . .; 
view.setLayoutParameters(lp); 

的值必須以像素爲單位。有幾個線程描述瞭如何將dp轉換爲像素。下面是this answer to another question一個代碼片段:

public static float convertDpToPixel(float dp,Context context){ 
    Resources resources = context.getResources(); 
    DisplayMetrics metrics = resources.getDisplayMetrics(); 
    float px = dp * (metrics.densityDpi/160f); 
    return px; 
} 

您應該然後轉換成一int和分配到的lp中的一個字段前添加0.5F。

0
layout.setLayoutParams(new LinearLayout.LayoutParams(400,400)); 

從聲明中獲取參考後,使用上面的語句動態設置寬度anbd高度。如果您在xml中使用線性佈局,則使用LinearLayout.LayoutParams。其他人明智,如果它是不同的,然後使用該佈局params。第一個是寬度,第二個是聲明中的高度。如果有任何疑問只是在這裏提出。

0

你可以試試下面的代碼

DisplayMetrics metrics = getResources().getDisplayMetrics(); 
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams((int) (metrics.density * 100 + 0.5f), (int) (metrics.density * 150 + 0.5f)); 
lp.setMargins(5, 5, 0, 0); 

final ImageView imgRss = new ImageView(getApplicationContext()); 
imgRss.setLayoutParams(lp);