0

Eu tenho a seguinte função no meu app android:

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

}

Essa função criará uma bolinha de uma cor aleatória e eu quero que quando eu clique e arraste para algum lugar essa bolinha acompanhe meu dedo. Essa função está funcionando - a bolinha acompanha o meu dedo - porém, a bolinha só aparece em um quarto da tela...

Meu arquivo XMl:

<?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>

Alguma ideia do por que isso acontece? O que posso fazer para resolver?

3
  • qual é o tamanho da Imagem? Como você adicionou estas imagens ao seu projeto? 14/06/2016 às 16:05
  • tenta usar android:scaleType="centerCrop", talvez seja isso 14/06/2016 às 16:23
  • não deu certo... Continua dando a mesma coisa ;(
    – gui5711
    15/06/2016 às 23:57

1 Resposta 1

0

Você precisa adicionar largura e altura adequadas para que o layout fique dentro de sua tela.

    RelativeLayout layout = new RelativeLayout(getActivity());

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

ou

  RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(0, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layout.setLayoutParams(rlp);
1
  • Eu adiciono o tamanho pro meu relativeLayout?
    – gui5711
    15/06/2016 às 23:57

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .