如何基于按钮单击在Android应用程序中创建输入字段?

时间:2018-08-13 15:53:28

标签: java android xml android-layout android-studio

这是我的XML当前的样子:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Typ hier in welk cijfer u wilt komen te staan:"
    android:textSize="30sp"
    android:gravity="center"
    android:paddingTop="10dp"
    android:textStyle="bold"/>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/EditText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Vul hier het cijfer in"
        android:paddingTop="100dp"
        android:background="@null"
        android:paddingLeft="30dp"
        android:maxLength="4"
        android:inputType="numberDecimal"/>

    <Button
        android:id="@+id/Button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Volgende"
        android:layout_marginLeft="75dp"/>
</LinearLayout>

点击按钮后,我想在我的应用界面中添加10个EditText输入字段。谁能指出我该怎么做?谢谢。

1 个答案:

答案 0 :(得分:1)

尝试

LinearLayout mLayout = (LinearLayout) findViewById(R.id.linearLayout);
Button mButton = (Button) findViewById(R.id.my_button);
mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText = new EditText(TmyContext);
            editText.setLayoutParams(new 
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
LinearLayout.LayoutParams.WRAP_CONTENT));
            mLayout.addView(editText);
        }
    });