Imageview appears in only a quarter of the screen

Asked

Viewed 59 times

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 that when I click and drag somewhere this ball accompanies my finger. This function is working - the ball accompanies my finger - however, 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?

  • what is the size of the image? How did you add these images to your project?

  • try to use android:scaleType="centerCrop", maybe that’s what

  • didn’t work out... Keeps giving the same thing ;(

1 answer

0

You need to add adequate width and height for the layout to stay 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);
  • I add size to my relativeLayout?

Browser other questions tagged

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