android按钮布局代码,Android - 按下按钮时将textview添加到布局(示例代码)

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

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

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

答案

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

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:id="@+id/linearLayout">

android:id="@+id/editText"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

/>

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Add+"

/>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值