2014-06-05 56 views
10

我正在研究一個應用程序,我必須動態創建多個 EditText和Spinner。所以我開始尋找 的解決方案,因爲我沒有權限在XML文件中使用Invisible 屬性。我搜索了很多,只有stackoverflow得到了幾個例子 。我遵循他們並創建了這個程序。在Android中動態創建EditText

 **MainActivity.java code** 

public class MainActivity extends Activity { 

     RelativeLayout containerLayout; 
     static int totalEditTexts = 0; 
     Button button; 
     Context context; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    containerLayout = (RelativeLayout)findViewById(R.id.relative1); 
    button = (Button)findViewById(R.id.button1); 

    button.setOnClickListener(new View.OnClickListener() { 

    @Override 
    public void onClick(View arg0) { 
    // TODO Auto-generated method stub 

    totalEditTexts++; 
    if (totalEditTexts > 100) 
    return; 
    EditText editText = new EditText(getBaseContext()); 
    containerLayout.addView(editText); 
     editText.setGravity(Gravity.RIGHT); 
    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) editText.getLayoutParams(); 
     layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT; 
     layoutParams.setMargins(23, 34, 0, 0); 
    // RelativeLayout.LayoutParams() 
     editText.setLayoutParams(layoutParams); 
    //if you want to identify the created editTexts, set a tag, like below 
    editText.setTag("EditText" + totalEditTexts); 
       } 
      }); 

}}

當我運行這段代碼,它創建的EditText得到了單擊按鈕時。但只有一次。之後我不知道發生了什麼。無論是創建新的EditText還是重疊舊的EditText,否則不會創建多個EditText。

enter image description here

誰能解釋我什麼,我現在要做的,以解決此問題。

回答

8

我已經與使用的RelativeLayout和動態添加的東西簡單地更換RelativeLayout的的LinearLayout

5

問題解決我的問題是,如果你不設置視圖的相對位置,它重疊的情況其他。因此,當您點擊並添加新視圖時,新視圖將被添加,但它們會相互重疊。但添加一個LinearLayout,視圖可以在另一個之下顯示,因爲您可以將方向設置爲垂直。