Create button via code

Asked

Viewed 2,999 times

5

It is possible to create a Button through code, rather than design mode (xml)?

For example: I will create a screen with a EditText, enter a number, and click on a Button.

After that, it will be created x (typed number) EditText below the button.

  • Have you looked at the official Google documentation ? It’s very good, I think you will be able to get your question !

  • Yes, I have, and I haven’t found anything specific about it :/

1 answer

4


First you need to define where you will put 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 that, in your code you can add a 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);
  • 1

    It worked. Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.