2014-05-03 25 views
-4

例如,給定:是否可以在Android中創建一個表單字段列表?

String[] formFields = {"name","description","notes"}; 

我可以創建一個使用該數組中的Android的EditText字段的列表,而不是硬編碼的EditText字段?

+0

是的,這是可能的,任何其他問題? –

+0

對不起,我是Java和Android初學者,只是想學習如何做。我在最後一小時搜索了一下,試圖找到一個關於如何這樣做的例子,但找不到任何例子。 – sjsc

+0

我會盡快寫出正確的答案。 –

回答

1

你可以做這樣的事情:

String[] array = new String[] { "A", "B", "C" }; 

int previousId = 0; 

// Loop through all the Strings in the array 
for(int i = 0; i < array.length; i++) { 

    // Get the text from the array 
    String text = array[i]; 

    // Create a new EditText 
    EditText editText = new EditText(context); 

    // To add the Rules for the position of the views later on we need to define an id. 
    // In this case I assign the index in the array as Id, but in your app you should define 
    // ids in values/ids.xml like this: <item name="firstEditText" type="id" /> and use these 
    editText.setId(i + 1); 

    // Set the text for the new EditText 
    editText.setText(text); 

    // Create the LayoutParams 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 

    // Add the rules where to place the view. 
    if(i == 0) { 

     // The first EditText will be placed at the top of the parent. 
     params.addRule(RelativeLayout.ALIGN_PARENT_TOP); 

    } else { 

     // All EditTexts after the first one are placed below the previous one. 
     params.addRule(RelativeLayout.BELOW, previousId); 

    } 

    // We save the id of this EditText so we can position the next EditText below it. 
    previousId = editText.getId();  

    // Add the view to your layout - in this case a RelativeLayout - with the LayoutParams we defined above 
    relativeLayout.addView(editText, params); 
} 
+0

這太棒了!非常感謝Xaver! – sjsc

+0

你有沒有可能提出很多答案?雖然我明白它不會有太大的好處。這種被稱爲連續投票的做法屬於投票欺詐行爲,並且令人不悅。它會在接下來的24小時內自動翻轉。這樣做沒有懲罰,但如果你繼續從事這種行爲,你可能會被禁止或面臨其他限制。 [這裏您可以找到更多關於序列upvoting的信息](http://meta.stackexchange.com/a/126857)。還有其他選項可以獎勵回答者,使其超越賞金和接受賞金系統。 –

+0

作爲一名初學者,我實際上是在等待您的回覆時閱讀其他Android答案。我應該刪除這些投票嗎? – sjsc

相關問題