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:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dinamic_textview);
final LinearLayout layout = (LinearLayout) findViewById(R.id.root_layout);
final Button bn = (Button) findViewById(R.id.btnaddnewtext);
bn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TextView tv1 = new TextView(v.getContext());
tv1.setText("Show Up");
layout.addView(tv1);
}
});
}
Layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns: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">
<Button
android: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:-
LinearLayout myLayout = (LinearLayout)findViewById(R.id.mLayout);
Button bn = (Button) findViewById(R.id.button2);
bn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView tv1 = new TextView(getApplicationContext());
tv1.setText("Show Up");
myLayout .addView(tv1);
}
});
Post a Comment for "Android: How To Create Dynamic View Elements On Button Click"