Jeremy
Jeremy

Reputation: 3809

How to add button using layout both defined in the main.xml?

I created the button in the main.xml file and initialized it in the activity file but I am not sure how to get the button to appear on screen using the layout defined in the xml. Can anyone help me with this?

public class MyTasteActivity extends Activity implements View.OnClickListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        tv.setText("Hello, Android");

        Button collectionBtn = (Button) findViewById(R.id.collectionBtn);

    }

    public void collectionBtn(View v) {
        Toast.makeText(getApplicationContext(), "Collection was pressed", Toast.LENGTH_LONG).show();
    }

    public void onClick(View v) {}
}

XML File:

    <LinearLayout
        android:layout_width="310px"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button
            android:id="@+id/collectionBtn"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="collectionBtn"
            android:text="Collection" />
        <Button
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 2" />

        <Button
            android:id="@+id/button3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 3" />

        <EditText
            android:id="@+id/txt"
            android:layout_width="fill_parent"
            android:layout_height="300px" />

        <Button
            android:id="@+id/button4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 4" />

        <Button
            android:id="@+id/button5"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 5" />
    </LinearLayout>

</ScrollView>

Upvotes: 1

Views: 620

Answers (1)

Austyn Mahoney
Austyn Mahoney

Reputation: 11408

Use setContentView() to tell Android what layout file to use for you Activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.xml_file_name_here);
}

Upvotes: 3

Related Questions