单击按钮时,我想动态创建EDITTEXT并垂直显示它们。我有这段代码,但它只创建了一个EditText。我哪里错了?感谢您的帮助。
private LinearLayout containerLayout;
static int totalEditTexts = 0;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_category);
containerLayout = (LinearLayout)findViewById(R.id.relative1);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
totalEditTexts++;
EditText editText = new EditText(getBaseContext());
containerLayout.addView(editText);
editText.setGravity(Gravity.LEFT);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) editText.getLayoutParams();
layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
layoutParams.setMargins(23, 34, 0, 0);
editText.setLayoutParams(layoutParams);
editText.setTag("EditText" + totalEditTexts);
}
});
}
如果您的add_category.xml
看起来像这样,您的示例就可以很好地工作:https://gist.github.com/akodiakson/9d37e3e48d0798d106c3
所以我猜想您的Activity
布局可能有点偏离。