简体   繁体   English

Android 动态添加 EditText

[英]Android add EditText dynamically

at the click of the button, I want to create EDITTEXT dynamically and display them vertically.单击按钮时,我想动态创建 EDITTEXT 并垂直显示它们。 I have this code but it just creates one EditText.我有这个代码,但它只创建了一个 EditText。 Where am I wrong?我哪里错了? Thanks for your help.谢谢你的帮助。

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);
        }
    });

} }

Your example works perfectly if your add_category.xml were to look like this: https://gist.github.com/akodiakson/9d37e3e48d0798d106c3如果您的add_category.xml看起来像这样,您的示例就可以完美add_category.xmlhttps : add_category.xml

So I'm guessing your Activity layout might be a little bit off.所以我猜你的Activity布局可能有点偏离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM