简体   繁体   中英

Android - Make Sure ImageView Stays on Screen

I have a Android project where I have an ImageView that moves to the left every time a button is pressed using

tButton.setOnTouchListener(new RepeatListener(10, 10, new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {                    
             player1.setX(player1.getX() - 1);
        }
}));

I don't want this ImageView to leave the screen, and so I've tried adding another ImageView to the edge, and tried using

tButton.setOnTouchListener(new RepeatListener(10, 10, new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            Rect p1 = new Rect();
            player1.getHitRect(p1);

            Rect sL = new Rect();
            lSide.getHitRect(sL);

          if(Rect.intersects(p1, sL))
            {
                player1.setX(player1.getX() + 100);
            }
            else
            {
                player1.setX(player1.getX() - 1);
            }
        }
}));

The problem is that after the two objects interest, the onClick method never seemed to get called again. Is there something that I'm forgetting to do, or is there an easier way to solve this problem? Thanks

There's an easier way to solve the problem. Use imageView.getLocationOnScreen() to get the x and y position of the view on screen. Then you can check and see if moving it again would cause you to have a negative X (move off the screen to the left) or if X+imageView.getWidth()>screen_width (move off to the right).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM