How to create a textView by code in a specific location of the activity?

1

I would like to know how to choose where the textView created by code will appear, because by default it is created at the top left of activity .

activity:

package genesysgeneration.classsound;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

        TextView tv = new TextView(this);
        tv.setText("lshdajshdlajsdkl");

        RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
        relativeLayout.addView(tv);

    }
}
    
asked by anonymous 22.03.2017 / 00:43

1 answer

0

To accomplish this feat is to use the RelativeLayout.LayoutParams , passing the getLayoutParams() in the view window. Here is an example using a simple button: Jon Snow . See comments. See:

// RelativeLayout referente ao XML
RelativeLayout relativeLayout  = (RelativeLayout) findViewById(R.id.relative);

// botão a ser positionado
Button btnJonSnow= new Button(this);
btnJonSnow.setText("Jon Snow");

// definição da largura e altura do botão
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
  RelativeLayout.LayoutParams.WRAP_CONTENT,
  RelativeLayout.LayoutParams.WRAP_CONTENT);
relativeLayout.addView(btnJonSnow, layoutParams);

//propriedades do Relative Layout para o posicionamento
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) btnJonSnow
  .getLayoutParams();
rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
btnJonSnow.setLayoutParams(rlp);

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/relative">
</RelativeLayout>

See below the basic placements:

Top / Left

rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

Top / Right

rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

Footer / Left

rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.ALIGN_PARENT_LEFT);

Footer / Right

rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.ALIGN_PARENT_RIGHT);

Center vertical / horizontal

rlp.addRule(RelativeLayout.CENTER_VERTICAL,RelativeLayout.CENTER_HORIZONTAL);

Formoredetailsandplacements,see in the documentation .

    
22.03.2017 / 04:27