0

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
eastwater
  • 4,624
  • 9
  • 49
  • 118

2 Answers2

1

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);
배준모
  • 591
  • 5
  • 12
0

you have to add a 1LinearLayout.LayoutParamsto theTextView` look at this answer

Damir Mailybayev
  • 1,031
  • 1
  • 9
  • 14