Brian
Brian

Reputation: 1989

Why can I not add a TextView to my LinearLayout in Android?

I am having a bunch of trouble adding a TextView to my LinearLayout. Here is what I have:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="some button text" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout mainLayout = (LinearLayout)findViewById(R.id.main_layout);
        TextView textView = new TextView(this);
        textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        textView.setText("Hello, world!");

        mainLayout.addView(textView);
    }
}

I don't get any errors in LogCat, it just doesn't work.

Any ideas?

Upvotes: 0

Views: 63

Answers (3)

Emmanuel Mtali
Emmanuel Mtali

Reputation: 4963

Make sure the spacing between your views is correct

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some button text" />

</LinearLayout>

You can also try mainLayout.addView(newView, 0); to add it before the button for verification

Upvotes: 1

Xerox23
Xerox23

Reputation: 153

Brian is right. There is also an typo in the first line. I guess it should be android.com

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

and not android/com.

Upvotes: 0

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37584

There is no space for your TextView because Button is taking them all.

<Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="some button text" />

Change it to wrap_content

Upvotes: 2

Related Questions