Search code examples
androidandroid-layoutviewandroid-relativelayout

Set X and Y of a view onclick not changing position


I am trying to programatically change the position of a TextView. I create the TextView in code and display it. Everything is working however the TextView stay in the top left corner of the screen regardless of and changes to setX or setY on it.

This is my code.

 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            textView = new TextView(MainActivity.this);
            textView.setText("Test");
            textView.setPadding(10, 10, 10, 10);

            RelativeLayout Screen = (RelativeLayout) findViewById(R.id.screenRelativeLayout);

            Typeface face=Typeface.createFromAsset(getAssets(),"fonts/shablagooital.ttf");
            textView.setTypeface(face);

            Display display = getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            int screenwidth = size.x;
            int screenheight = size.y;
            Random randdisp = new Random();

            int randscreenwidth = randdisp.nextInt(screenwidth) + 1;
            int randscreenheight = randdisp.nextInt(screenheight) + 1;

            textView.setX(200);
            textView.setY(200);

            Screen.addView(textView);

Thanks for your help.

Nicholas


Solution

  • You can use LayoutParams:

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); 
    params.setMargins(200, 200, 0, 0);
    Screen.addView(textView, params);