Dynamically adding a textView into a LinearLayout:
layout XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
Java code:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main_layout);
TextView textView = new TextView(getApplicationContext());
textView.setText("Hello World");
linearLayout.addView(textView);
The textView did not show up. miss anything? Thanks.
UPDATE
Thanks for the answers. it works even without the layoutParams.
The issue is that the LinearLayout is in the middle of a UI view tree, and the following is needed:
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="mypackage.MainActivity"
tools:showIn="@layout/app_bar_main
for a Navigation Drawer activity.