How to create a textView by code in a specific Activity location?

Asked

Viewed 531 times

1

I wonder how to choose the place where the textView created by code will appear, because by default it is created at the top left of the 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);

    }
}

1 answer

0


To accomplish this feat is using the Relativelayout.Layoutparams, passing the method getLayoutParams() in view desired. Below follows an example using a simple button: Jon Snow. See comments. View:

// 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 positions:

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);

Vertical/horizontal center

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

inserir a descrição da imagem aqui

For more details and positions, see in the documentation.

Browser other questions tagged

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