casillas
casillas

Reputation: 16813

Add a Button on the View

I have the following axml.

<LinearLayout
   android:layout_width="wrap_content"
   android:layout_height="360dp"
   android:id="@+id/viewA">
   <View
       android:layout_width="wrap_content"
       android:layout_height="360dp"
       android:id="@+id/viewB" />
</LinearLayout>

I want to add a button on the ViewB programmatically. I could not able to figure that out since View does not have addView method.

Upvotes: 1

Views: 36

Answers (1)

ArtKorchagin
ArtKorchagin

Reputation: 4853

Use FrameLayout instead of View. View does not have a children.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewA"
    android:layout_width="wrap_content"
    android:layout_height="360dp">

    <FrameLayout
        android:id="@+id/viewB"
        android:layout_width="wrap_content"
        android:layout_height="360dp" />
</LinearLayout>

Just add in you code:

    Button button = new Button(this);
    button.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
    FrameLayout group = (FrameLayout) findViewById(R.id.viewB);
    group.addView(button);

Upvotes: 2

Related Questions