简体   繁体   中英

Creating an EditText when a Button is clicked

I want to create an onclick event that creates an EditText . I have tried the following code but it erases everything and creates a new Layout with a EditText .

public class MainActivity extends Activity {

    ArrayList<Contact> contact;
    Contact currentcontact;
    EditText nameArea,emailArea,phoneArea;
    int emails=1;
    int phones=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nameArea=findViewById(R.id.name_area);
        emailArea=findViewById(R.id.e1);
        phoneArea=findViewById(R.id.p1);
        contact=new ArrayList<>();
    }

    public void buttonclick(View v){
        if(v.getId()==R.id.addemail){
            createemaileditview();
        }
        if(v.getId()==R.id.addphone){
            createphoneeditview();
        }
        if(v.getId()==R.id.save){

        }
        if(v.getId()==R.id.cancel){
        }

    }
    protected void createemaileditview(){
        LinearLayout outerLayout=new LinearLayout(this);
        outerLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
        outerLayout.setOrientation(LinearLayout.VERTICAL);
        EditText email=new EditText(this);
        email.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT,1f));
        outerLayout.addView(email);
        setContentView(outerLayout);
        emails++;
    }
    protected void createphoneeditview(){
        phones++;
    }
}

There is a slight mistake in your code. You are replacing your main activity layout with outerLayout by calling setContentView(outerLayout) . You can get your desired functionality by adding your editText to your main activity layout instead of creating new layout and replacing all the existing stuff. See the link for complete code. Dynamically add Edittext to a relative layout under an existing editText

If you are only have one EditText to create or you keep want to keep the design under control easily, the better keep them in invisible with View.INVISIBLE at the beginning, not gone by View.GONE. With this your design can be simple.

From android;

View.GONE This view is invisible, and it doesn't take any space for layout purposes.

View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.

See

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