Android: How To Create Dynamic View Elements On Button Click
It looks to be a simple problem but I am struggling since 2 days. I want to create a textView dynamically on Button Click. Here is sample peice of code public void onCreate(Bundle
Solution 1:
layout isnt defined as far as I can see, try findViewById on the layout and then set a child element on it, then it should work
Solution 2:
Hi read my earlier post, it contains the sample code. (In the UI there is an edittext and a button, after you click the button the new textview shows up with the entered text.) I think this will help for you.
I updated the answer with the working code.
The code only in onCreate() method:
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dinamic_textview);
finalLinearLayoutlayout= (LinearLayout) findViewById(R.id.root_layout);
finalButtonbn= (Button) findViewById(R.id.btnaddnewtext);
bn.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v) {
TextViewtv1=newTextView(v.getContext());
tv1.setText("Show Up");
layout.addView(tv1);
}
});
}
Layout xml:
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/root_layout"><Buttonandroid:id="@+id/btnaddnewtext"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Add"
/></LinearLayout>
Solution 3:
Get the layout in which you want the TextView to showup from your layout.xml.
Then add your TextView to that Layout like so:-
LinearLayoutmyLayout= (LinearLayout)findViewById(R.id.mLayout);
Buttonbn= (Button) findViewById(R.id.button2);
bn.setOnClickListener(newOnClickListener() {
publicvoidonClick(View v) {
TextViewtv1=newTextView(getApplicationContext());
tv1.setText("Show Up");
myLayout .addView(tv1);
}
});
Post a Comment for "Android: How To Create Dynamic View Elements On Button Click"