java – How to set the y-value of a framelayout to 3/4 of the screenhight?-ThrowExceptions

Exception or error:

I want to develop a game where you have to hold your finger on a screen until the “water” rises to 3/4 of the screen height (in my case between 1544 and 1623 this area is marked by a frame layout).
How can I make the position of the frame layout and the values of the maximum&minimum depend on the screen size?

public class GameActivity extends AppCompatActivity {

    Button button_game;
    TextView water;
    Handler handler = new Handler();
    boolean pushingDown = false;
    int wincounter;
    int maximum = 1623;
    int minimum = 1544;
    FrameLayout frameLayout;
    int height;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        frameLayout = findViewById(R.id.frameLayout);

        button_game = findViewById(R.id.button_game);
        water = findViewById(R.id.water);

        button_game.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    pushingDown = true;
                    handler.post(repeater);

                }
                if (event.getAction() == MotionEvent.ACTION_UP) {

                    pushingDown = false;

                    ViewGroup.LayoutParams params = water.getLayoutParams();

                    if (params.height > minimum && params.height <= maximum) {
                        wincounter = 1;
                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        intent.putExtra("wincounter", wincounter);
                        startActivity(intent);
                    }

                    params.height = 1;
                }

                return GameActivity.super.onTouchEvent(event);

            }
        });

    }

    Runnable repeater = new Runnable() {
        @Override
        public void run() {
            ViewGroup.LayoutParams params = water.getLayoutParams();

            if (params.height > maximum) {
                Intent intent = new Intent(getApplicationContext(), LoseActivity.class);
                startActivity(intent);

            } else if (pushingDown) {
                params.height = params.height + 2;
                water.setLayoutParams(params);
                handler.post(this);
                //repeating while touched
            }
        }
    };
}
How to solve:

You can get height of display from DisplayMeterics like

final int height = getContext().getResources().getDisplayMetrics().heightPixels;
final int oneThird = height/3;

params.height = oneThird;
water.setLayoutParams(params);

Leave a Reply

Your email address will not be published. Required fields are marked *