Add views dynamically android -
i trying add textviews dynamically activity , able added textviews getting added next each other on right side , want have each textview underneath each other.
here code:
@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); linearlayout linearlayout = (linearlayout)findviewbyid(r.id.linearlayout); for(int x = 0;x < 10; x++){ linearlayout layout = new linearlayout(this); textview tv = new textview(this); tv.settext("text view "+x); layout.setorientation(linearlayout.horizontal); layout.addview(tv); linearlayout.addview(layout); } }
main xml:
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:paddingbottom="@dimen/activity_vertical_margin" tools:context=".mainactivity"> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearlayout" android:orientation="horizontal"></linearlayout> </relativelayout>
you can way:
you have set orientation vertical of parent linear layout:
your xml should looks this:
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:paddingbottom="@dimen/activity_vertical_margin" tools:context=".mainactivity"> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearlayout" android:orientation="vertical"></linearlayout> </relativelayout>
your java code should looks this:
for(int x = 0;x < 10; x++){ textview tv = new textview(this); tv.settext("text view "+x); linearlayout.addview(tv); }
hope you.
Comments
Post a Comment