1

I just started android and I tried below questions to get this answer before posting it here:

Android - Adding layout at runtime to main layout

Add button to a layout programmatically

Dynamically adding a child to LinearLayout with getting each child's position

And I am still not able to add a button to linear layout :(

Below is the code for activity, please let me know where I am wrong:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.activity_main, null);

        Button btn = new Button(this);
        btn.setId(123);
        btn.setText("Welcome to WI FI World");
        layout.addView(btn);
    }

And xml looks like below:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</LinearLayout>
Community
  • 1
  • 1
Atul
  • 1,694
  • 4
  • 21
  • 30
  • You need to add your linear layout to the page. Im pretty sure those arent the same linear layouts. and so you are adding a button to one that isnt shown – IAmGroot Sep 03 '12 at 18:12

3 Answers3

2

Try assigning an id to your layout then add the button to the layout.

Im pretty sure those 2 layouts are not the same, so you are infact adding a button to a layout that is never displayed.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LinearLayout layout = (LinearLayout) findViewById(R.id.lnr_main);

    Button btn = new Button(this);
    btn.setId(123);
    btn.setText("Welcome to WI FI World");
    layout.addView(btn);
}

With Layout assigned an id

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

</LinearLayout>
IAmGroot
  • 13,760
  • 18
  • 84
  • 154
1

Give an id to your linearLayout.

Then in your code

LinearLayout layout = (LinearLayout)findViewById(R.id.given_id);

Keep the rest the same, should work.

Jose L Ugia
  • 5,960
  • 3
  • 23
  • 26
1

Take the Id for LinearLayout in XML and in jave code use that id of LinearLayout from XML

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

</LinearLayout>

In onCreate():

LinearLayout linear=(LinearLayout)findViewById(R.id.linear);

 //Select widgets
 linear.addView()
Abhi
  • 8,935
  • 7
  • 37
  • 60