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

问题描述 投票:15回答:1

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

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

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

android textview textfield
1个回答
32
投票

此代码包含您想要的内容。 (视图显示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;
}

而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+"
/>

© www.soinside.com 2019 - 2024. All rights reserved.