Android的 - 添加的TextView到布局时按钮是pressed [英] Android - Add textview to layout when button is pressed

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

问题描述

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

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

我想使它所以每次文字输入到文本字段,添加按钮是pressed,一个新的文本视图添加到它下面的垂直布局与用户键入的文本领域

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.

推荐答案

这code包含你想要什么。 (该视图显示一个EditText和一个按钮,当您点击按钮上的文本将增加的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是:

And the xml is:

<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的 - 添加的TextView到布局时按钮是pressed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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