我想开发一款游戏,您必须将手指放在屏幕上,直到“水”上升到屏幕高度的3/4(在我的情况下,在1544年和1623年之间,该区域由框架布局标记)。
如何使框架布局的位置以及最大和最小的值取决于屏幕尺寸?

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

最佳答案

您可以从DisplayMeterics获得显示的高度,例如

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

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

07-24 18:56