我寫了一個示例代碼,看看它可以幫助你
public class ActivityMain extends Activity {
LinearLayout main;
private int id = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
main = (LinearLayout) findViewById(R.id.parent);
main.setOrientation(LinearLayout.VERTICAL);
final EditText editText = (EditText) findViewById(R.id.et_count);
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
final int count = Integer.parseInt(editText.getText()
.toString());
addEditText(count);
}
});
}
private void addEditText(int count) {
for (int i = 0; i < count; i++) {
LinearLayout editTextLayout = new LinearLayout(this);
editTextLayout.setOrientation(LinearLayout.VERTICAL);
main.addView(editTextLayout);
EditText editText1 = new EditText(this);
editText1.setId(id++);
editTextLayout.addView(editText1);
}
}
}
和佈局的test.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/parent"
android:padding="10dp" >
<EditText
android:id="@+id/et_count"
android:layout_width="100dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
增添風采
editTextLayout.setTextAppearance(getApplicationContext(), R.style.boldText);
你可以把所有的在Java中的附件/循環邏輯,但只是膨脹現有的XML資源 - 所以不需要在Java層中的樣式等。 –