Insert marginRight in a Textview from Java code

Asked

Viewed 118 times

2

I made the following code to insert Textviews in a Linearlayout already defined.

public void inserirLacunas(){
    LinearLayout ll = (LinearLayout) findViewById(R.id.layoutLetras);

    for(int i = 0; i < palavraCerta.length(); i++){
        TextView lacuna = new TextView(this);
        lacuna.setText("_");
        lacuna.setTextSize(40);
        ll.addView(lacuna);
    }
}

My question is: how can I put one marginRight in Textview gap, so that when the code is executed, do not take the Textviews very close to one another?

palavraCerta is another variable created previously in the code, which does not matter in this doubt

1 answer

3


You must create an object of the type Linearlayout.Layoutparams, indicate the parameters and assign it to the Textview:

public void inserirLacunas(){
    LinearLayout ll = (LinearLayout) findViewById(R.id.layoutLetras);

    for(int i = 0; i < palavraCerta.length(); i++){
        TextView lacuna = new TextView(this);
        lacuna.setText("_");
        lacuna.setTextSize(40);

        //Ciar parâmetros 
                LinearLayout.LayoutParams params = 
               new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
                                             LinearLayout.LayoutParams.WRAP_CONTENT);


        //Definir as margens
        params.setMargins(left, top, right, bottom)//Introduza os valores pretendidos.
        //Atribuir os parâmetros ao TextView
        lacuna.setLayoutParams(params);
        ll.addView(lacuna);
    }
}
  • What should be the import for "Layoutparams"?

  • Depends, it’s best to change to LinearLayout.LayoutParams.WRAP_CONTENT

Browser other questions tagged

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