Android add edittext field on click of (+) button and remove by click of (-)

孤街浪徒 提交于 2019-12-06 22:11:30
private void addEditView() {
        // TODO Auto-generated method stub
          LinearLayout li=new LinearLayout(this);
          EditText et=new EditText(this);
          Button b=new Button(this);

          b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                int pos=(Integer) v.getTag();
                mainLayout.removeViewAt(pos);

            }
        });

          b.setTag((mainLayout.getChildCount()+1));
    }

call this function when you click on a addEditText button.

Use this code in your activity :

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    // TODO Auto-generated method stub

     if (event.getKeyCode() == KeyEvent.KEYCODE_PLUS)
     {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0)
            {
                LinearLayout mLinearLayout = new LinearLayout(this);
                mLinearLayout = (LinearLayout)findViewById(R.id.mylinearlayout);

                                EditText lEditText = new EditText(this);
                            lEditText.SetText("Text Here");
                            mLinearLayout.addView(lEditText);

                    }
            }
    return super.dispatchKeyEvent(event);
}

You should create Android Layout(maybe LinearLayout or TableLayout) and than create view in java code(Android Activity)

Simple example;

View view = new View(this);

If view create successfully you can add this code --> .addView(view); or if view already added you can remove this code sample --> .removeView(view);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!