Skip to content Skip to sidebar Skip to footer

How Do I Add New Textviews Each Time A Button Is Pressed?

I am very new to Android coding and I have a question about creating textviews dynamically when a button is pressed. I have figured out how to add textviews to another activity whe

Solution 1:

private LinearLayout mLayout;
private EditText mEditText;
private Button mButton;

@OverridepublicvoidonCreate(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());
TextViewtextView=newTextView(this);
textView.setText("New text");

}

private OnClickListener onClick() { return new OnClickListener() {

@OverridepublicvoidonClick(View v) {
        mLayout.addView(createNewTextView(mEditText.getText().toString()));
    }
};

}

private TextView createNewTextView(String text) {
finalLayoutParamslparams=newLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
finalTextViewtextView=newTextView(this);
textView.setLayoutParams(lparams);
textView.setText("New text: " + text);
return textView;

}

add this in 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+"
/>

Post a Comment for "How Do I Add New Textviews Each Time A Button Is Pressed?"