2012-05-03 18 views
10

是否ViewGroup.addView克隆LayoutParams數據進入裏面或鏈接到它?我是否可以重複使用LayoutParams的同一個實例並將多個調用與addView()進行不同視圖?我可以重新使用ViewGroup.addView的LayoutPrams嗎?

在apidoc中沒有關於它的內容。

WOW

答案是否定的(經實驗檢驗):

public class SymbolPadActivity extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 

    RelativeLayout.LayoutParams labelParams; 

    /* 
    * This block to reuse is not working 
    labelParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    labelParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 
    labelParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); 
    */ 


    RelativeLayout mover = new RelativeLayout(this); 

    TextView textView; 
    for(int leftMargin = 0; leftMargin<3000; leftMargin += 100) { 
     for(int topMargin=0; topMargin<800; topMargin += 40) { 

      // I can't omit these 3 lines 
      labelParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      labelParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 
      labelParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); 

      labelParams.leftMargin = leftMargin; 
      labelParams.topMargin = topMargin; 

      textView = new TextView(this); 
      textView.setText("(" + leftMargin + "," + topMargin + ")"); 
      mover.addView(textView, labelParams); 

     } 
    } 




    RelativeLayout.LayoutParams moverParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    moverParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 
    moverParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); 
    moverParams.leftMargin = 0; 
    moverParams.topMargin = 0; 

    RelativeLayout stator = new RelativeLayout(this); 
    stator.addView(mover, 0, moverParams); 

    setContentView(stator); 


} 

}

+0

我再利用我的PARAMS,它的工作!但我的cameraview停止工作。 :/我甚至不能在LayoutParms構造函數中重用一個參數來創建另一個O_O。 –

回答

5

沒有任何關於它apidoc。

這意味着無論當前的實施情況如何,您都需要做出更保守的選擇,因爲實施可能會發生變化。

因此,您需要假設不重複使用LayoutParams的實例以用於不同的Views

FWIW,AFAICT,無論如何這是真的 - ViewGroup似乎沒有複製。

1

這是一個老問題,但似乎有一個更新的答案:

的的LayoutParams有抄襲其他 來源構造:http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html

ViewGroup.LayoutParams(ViewGroup.LayoutParams source) 

這表明不能再使用它,但也許創建1佈局params對象與你需要的一切,然後只需撥打

new LayoutParams(someLayoutParamsToReUse) 

在我的情況,我想s et按鈕的佈局參數與另一個按鈕相同。我最初嘗試:

button.setLayoutParams(button2.getLayoutParams()); 

這將無法正常工作,但是這應該:

button.setLayoutParams(new LayoutParms(button2.getLayoutParams))' 
相關問題