Generate button board by code in Android Studio

3

I'm working on an android application and I need to create a board (made of buttons).

I already generated the board from the code of my java class, but the problem is that the buttons go out of sight (they leave the screen). I have already tried several things with the LayoutParams but nothing has worked for me. I hope you can help me thanks.

Here is the code generated by the board (buttons)

    botones = new Button[numLetras];

    for (int i = 0; i < numLetras; i++ )
    {
        botones[i] = new Button(layout.getContext());
        botones[i].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                                                 LinearLayout.LayoutParams.WRAP_CONTENT));
        botones[i].setText(texto[i]);
        botones[i].setId(i + 1 );
        layout.addView(botones[i]);

    }

and here is a picture of how it looks. (The text that has to appear is "TEXTEXAMPLE")

    
asked by Adelmo Cruz 08.09.2016 в 21:08
source

3 answers

2

You have to put the Weight

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,1);

    botones[i].setLayoutParams(layoutParams);

If what you want is to have it in a single line you can do this. This is how TEXTEXTEMPLOY should appear on a single line.

    
answered by 08.09.2016 в 23:32
0

Maybe it's good to try with a GridView . A GridView is a ViewGroup that shows the elements in a scrollable two-dimensional grid. The elements of the grid are automatically inserted according to the layout using a ListAdapter .

Learn more.

    
answered by 08.09.2016 в 23:11
0

This can be said to be relatively simple, the buttons (or views) will be evenly distributed if we assign them a weight of 1

    //Obtiene instancia de contenedor padre
    LinearLayout container = (LinearLayout) findViewById(R.id.layout);
    //Definimos un texto en base al cual se crearan los botones.
    String s = "TEXTOEJEMPLO";
    String[] letras = s.split("");;//Convierte texto a arreglo Char

    int cantidadBotones = s.length(); //Obtenemos la cantidad de  botones a dibujar.
    for (int i = 0; i < cantidadBotones; i++) {
        Button bn = new Button(getApplicationContext());
        bn.setId(1 + 2000); //Define ids
        bn.setMinHeight(0);
        bn.setMinimumHeight(0);
        bn.setPadding(0,0,0,0); //Elimina padding
        bn.setTextSize(14);
        bn.setText(letras[i+1]); //Asigna letra.
        //Crea contenedor con peso de 1 para cada elemento.
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f);
        bn.setLayoutParams(params);
        //Agrega vista a contenedor padre.
        container.addView(bn);
    }

In this way we can add the buttons with the same weight and distribute them evenly.

    
answered by 13.12.2016 в 23:33