Android - 按下按钮时将文本视图添加到布局 [英] Android - Add textview to layout when button is pressed

查看:11
本文介绍了Android - 按下按钮时将文本视图添加到布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So right now I have a text field with a button (add+) below it.

我希望每次在文本字段中输入文本并按下添加"按钮时,都会在其下方的垂直布局中添加一个新的文本视图,其中包含用户在字段中键入的文本.

I would like to make it so every time text is entered into the Text Field, and the Add button is pressed, a new text view is added to a vertical layout below it with the text that the user typed in the field.

我不想简单地使文本视图不可见,然后在单击时可见,因为我希望他们能够添加多个文本视图,无论他们键入什么文本.

I do not want to simply make a text view invisible, then visible when clicked, because I would like them to be able to add more than one text view with whatever text they type.

推荐答案

这段代码包含你想要的.(视图显示一个 EditText 和一个 Button,单击按钮后文本将添加到 LinearLayout)

This code contains what you want. (The view show an EditText and a Button, after you click on the button the text will add to the 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+"
/>

这篇关于Android - 按下按钮时将文本视图添加到布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆