【问题标题】:Android - Add textview to layout when button is pressedAndroid - 按下按钮时将文本视图添加到布局
【发布时间】:2011-10-19 07:48:08
【问题描述】:

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

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

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

【问题讨论】:

标签: android textview textfield


【解决方案1】:

此代码包含您想要的内容。 (视图显示一个 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+"
/>

【讨论】:

  • 我们如何将文本视图添加到另一个活动?我想通过在我的第二个活动中单击按钮将文本视图添加到我的第一个活动
  • @KrauszLórántSzilveszter,请阅读以下主题以获取更多信息stackoverflow.com/questions/3216294/…
  • @kameny 你知道如何在物理键盘上按下回车键时将输入文本添加到新的文本视图吗?
  • 如果按钮在不同的片段中,你会怎么做?
猜你喜欢
  • 1970-01-01
  • 2016-02-13
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多