Create button via code

5

Is it possible to create a Button through code rather than design mode (xml)?

For example: I'll create a screen with a EditText , type a number, and click a Button .

After this, x (number entered) EditText is created below the button.

    
asked by anonymous 16.07.2015 / 18:12

1 answer

4

First you need to define where to place your button (a container, for example):

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

    <TextView
        android:id="@+id/tv_teste"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Texto" />

    <FrameLayout
        android:id="@+id/container_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

After this, in your code you can add Button to this container:

FrameLayout container = (FrameLayout) findViewById(R.id.container_button);

//Criando um botão passando o contexto
Button button = new Button(this);
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
button.setText("Algum texto");

//Adicionando o botão na tela
container.addView(button);
    
16.07.2015 / 18:52