简体   繁体   中英

Android add EditText dynamically

at the click of the button, I want to create EDITTEXT dynamically and display them vertically. I have this code but it just creates one 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

So I'm guessing your Activity layout might be a little bit off.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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