Android - 按下按钮时将textview添加到布局

use*_*609 15 android textfield textview

所以现在我有一个文本字段,下面有一个按钮(添加+).

我希望每次在文本字段中输入文本时按下"添加"按钮,新的文本视图将添加到其下方的垂直布局中,并带有用户在该字段中键入的文本.

我不想简单地使文本视图不可见,然后在单击时可见,因为我希望它们能够添加多个文本视图以及它们键入的任何文本.

kam*_*eny 33

此代码包含您想要的内容.(视图显示EditText和Button,单击按钮后文本将添加到LinearLayout)

    private LinearLayout mLayout;
private EditText mEditText;
private Button mButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mLayout = (LinearLayout) findViewById(R.id.linearLayout);
    mEditText = (EditText) findViewById(R.id.editText);
    mButton = (Button) findViewById(R.id.button);
    mButton.setOnClickListener(onClick());
    TextView textView = new TextView(this);
    textView.setText("New text");
}

private OnClickListener onClick() {
    return new OnClickListener() {

        @Override
        public void onClick(View v) {
            mLayout.addView(createNewTextView(mEditText.getText().toString()));
        }
    };
}

private TextView createNewTextView(String text) {
    final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    final TextView textView = new TextView(this);
    textView.setLayoutParams(lparams);
    textView.setText("New text: " + text);
    return textView;
}
Run Code Online (Sandbox Code Playgroud)

而xml是:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/linearLayout">
 <EditText 
    android:id="@+id/editText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
 />
<Button 
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add+"
/>
Run Code Online (Sandbox Code Playgroud)