ImageView appears in only one-fourth of the screen

0

I have the following function in my android app:

public void createBall()  {

    layout = new RelativeLayout(this);

    // Random choose color of ball
    int[] color={R.drawable.vermelho, R.drawable.azul, R.drawable.amarelo, R.drawable.verde};

    Random ran=new Random();
    int i=ran.nextInt(color.length);

    imageView = (ImageView) findViewById(R.id.littleBall);

    // Setting image resource
    imageView.setImageResource(color[i]);


    imageView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getActionMasked()) {
                case MotionEvent.ACTION_UP: {
                    createBall();
                }
                case MotionEvent.ACTION_MOVE: {
                    int[] array = new int[2];
                    int left = Math.round(event.getRawX())-100;
                    int top = Math.round(event.getRawY())-100;
                    imageView.setLeft(left);
                    imageView.setTop(top);
                }
            }
            return true;
        }
    });

}

This function will create a ball of a random color and I want it when I click and drag somewhere that ball accompanies my finger. This function is working - the ball accompanies my finger - but the ball only appears in a quarter of the screen ...

My XMl file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.teste.startGame">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/littleBall"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Any idea why this happens? What can I do to resolve it?

    
asked by anonymous 14.06.2016 / 17:49

1 answer

0

You need to add proper width and height for the layout to be inside your screen.

    RelativeLayout layout = new RelativeLayout(getActivity());

    RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(0, 100);
    layout.setLayoutParams(rlp);

or

  RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(0, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layout.setLayoutParams(rlp);
    
14.06.2016 / 18:17