eastwater
eastwater

Reputation: 5572

android dynamically create TextView not showing

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.

Upvotes: 0

Views: 1733

Answers (2)

배준모
배준모

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

Damir Mailybayev
Damir Mailybayev

Reputation: 1081

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

Upvotes: 0

Related Questions