例如,给定:是否可以在Android中创建一个表单字段列表?
String[] formFields = {"name","description","notes"};
我可以创建一个使用该数组中的Android的EditText字段的列表,而不是硬编码的EditText字段?
例如,给定:是否可以在Android中创建一个表单字段列表?
String[] formFields = {"name","description","notes"};
我可以创建一个使用该数组中的Android的EditText字段的列表,而不是硬编码的EditText字段?
你可以做这样的事情:
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);
}
是的,这是可能的,任何其他问题? –
对不起,我是Java和Android初学者,只是想学习如何做。我在最后一小时搜索了一下,试图找到一个关于如何这样做的例子,但找不到任何例子。 – sjsc
我会尽快写出正确的答案。 –