2012-12-17 72 views
0

我有一個需要添加一個或多個視圖的類。在這個例子中,單一的ImageView。 我可以添加意見沒有問題,並使用LayoutParameters對齊它們,但是當我嘗試將它們對齊或居中在垂直軸的某個位置時,它們要麼固定在頂部,要麼根本不出現(它們很可能不在視圖中)。
在構造函數中,我調用方法fillView(),這發生在設置所有維度之後。視圖將不會對齊或垂直居中

fillView()

public void fillView(){ 
    img = new ImageView(context); 
    rl = new RelativeLayout(context); 

    img.setImageResource(R.drawable.device_access_not_secure); 

    rl.addView(img, setCenter()); 
    this.addView(rl, matchParent()); 
} 

matchParent()

public LayoutParams matchParent(){ 
    lp = new RelativeLayout.LayoutParams(
      RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); 
    lp.setMargins(0, 0, 0, 0); 
    return lp; 
} 

setCenter()

public LayoutParams setCenter(){ 
    lp = new RelativeLayout.LayoutParams(
      RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); //This puts the view horizontally at the center, but vertically at the top 
    return lp; 
} 

同樣,添加諸如ALIGN_RIGHT或BELOW之類的規則也能正常工作,但ALIGN_BOTTOM或CENTER_VERTICALLY不會。

我試過使用這種方法和setGravity()一個LinearLayout提供,具有相同的結果。

+0

你能告訴我們'matchParent()'嗎?我懷疑你的'RelativeLayout'沒有使用全屏幕尺寸。 – Rawkode

+0

將其添加到問題中。不過,我應該注意到,我將佈局的backgroundColor設置爲綠色,以查看它是否在屏幕上,並且它填充整個視圖,因爲它應該。 –

回答

0

之前,雖然我仍然不知道爲什麼我的方法水平的工作,而不是垂直方向,我沒解決問題。發佈的方法奏效,問題隱藏在onMeasure()中。
我以前通過簡單地將它們傳遞給setMeasuredDimension()來設置尺寸。我通過將它們傳遞給layoutParams()來解決問題。我還改變了我在MeasureSpecs時使用的整數。

我改變了這個:

@Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){ 
     super.onMeasure(this.getT_Width(), this.getT_Heigth());  
     this.setMeasuredDimension(desiredHSpec, desiredWSpec); 
    } 


這樣:

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){ 
    final int desiredHSpec = MeasureSpec.makeMeasureSpec(this.getT_heigth(), MeasureSpec.EXACTLY); 
    final int desiredWSpec = MeasureSpec.makeMeasureSpec(this.getT_width(), MeasureSpec.EXACTLY); 
    this.getLayoutParams().height = this.getT_heigth(); 
    this.getLayoutParams().width = this.getT_width(); 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
    int width = MeasureSpec.getSize(desiredWSpec); 
    int height = MeasureSpec.getSize(desiredHSpec); 
    setMeasuredDimension(width, height); 
} 

getT_Width()getT_Heigth()是我用來獲取一些自定義維度設置我在其他地方的方法。 我希望這有助於某人。

0

你想要添加您ImageView您已經添加了RelativeLayout

+0

我想我應該這樣做,因爲如果我使用這個順序,圖像就會顯示出來,而不是相反。 –

+0

我要一起開始一個快速項目並且玩這個,給我十分鐘 – Rawkode