2014-05-03 29 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

相关问题