单击按钮动态添加和删除编辑文本

时间:2016-10-24 03:33:56

标签: java android-studio

我尝试使用Android studio动态添加和删除编辑文本。目前,我可以动态添加编辑文本,但我无法动态删除编辑文本。

这就是我的代码的样子:

// Declaration 
private LinearLayout containerLayout;
private LinearLayout.LayoutParams lpView;
private EditText[] editTextDisplay = new EditText[6];
private EditText editText;
private int totalEditTexts = 0;
private int showNo = 3;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    lpView = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(totalEditTexts < 3)
            {
                editText = new EditText(getActivity());
                containerLayout.addView(editText);
                //editText.setGravity(Gravity.RIGHT);

                lpView.width = LinearLayout.LayoutParams.MATCH_PARENT;
                editText.setLayoutParams(lpView);
                editText.setHint("Choice "+ showNo);

                // Creating an array to store the dynamic editText value
                editTextDisplay[totalEditTexts] = editText;

                // Incrementing count and show value at the end of every click
                totalEditTexts++;
                showNo++;
            }
        }
    });

    btnSub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(totalEditTexts > 2)
            {
                containerLayout.removeView(editText);
                editTextDisplay[totalEditTexts] = null;
                totalEditTexts--;
            }
        }
    });
}

感谢有人可以帮助我,谢谢!

0 个答案:

没有答案