Android - Add textview to layout when button is pressed
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开发者_如何学Python 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.
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;
}
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+"
/>
精彩评论