Reputation: 5572
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.
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.
Upvotes: 0
Views: 1733
Reputation: 601
add layoutParams. try this
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
TextView textView = new TextView(getApplicationContext());
textView.setLayoutParams(params);
textView.setText("Hello World");
linearLayout.addView(textView);
Upvotes: 1
Reputation: 1081
you have to add a 1LinearLayout.LayoutParamsto the
TextView`
look at this answer
Upvotes: 0