首页 > 解决方案 > Android 应用程序 - 如何将对象定位到屏幕的顶部和底部?

问题描述

我正在尝试创建一个简单的 android 应用程序来在屏幕的顶部和底部显示一个黑条,因为我不喜欢现在所有手机都有的圆角屏幕角的新趋势,而且目前似乎没有是不需要根电话的任何解决方案。我试图隐藏圆角以创建更传统和更美观的矩形显示器的外观,使用系统覆盖来绘制所有其他应用程序。这是我目前用于覆盖的代码,基于此https://gist.github.com/bjoernQ/6975256

wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

    overlayedButton1 = new Button(this);
    overlayedButton1.setBackgroundColor(-16777216);

    overlayedButton2 = new Button(this);
    overlayedButton2.setBackgroundColor(-16777216);

    WindowManager.LayoutParams params1 = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT);
    params1.gravity = Gravity.LEFT | Gravity.TOP;
    params1.x = 0;
    params1.y = 0;
    params1.width = 1080;
    params1.height = 100;
    wm.addView(overlayedButton1, params1);

    WindowManager.LayoutParams params2 = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT);
    params2.gravity = Gravity.LEFT | Gravity.BOTTOM;
    params2.x = 0;
    params2.y = 0;
    params2.width = 1080;
    params2.height = 100;
    wm.addView(overlayedButton2, params2);

结果是状态栏下方和导航栏上方的黑条,如图所示

https://i.stack.imgur.com/CbUYD.jpg

我是 Android 开发新手,所以不确定如何将条形图定位到屏幕的绝对顶部和底部?

另一个问题是,当打开以横向模式运行的应用程序时,我的叠加应用程序的黑条也会旋转,因此它们位于屏幕的两侧。

我已将 android:screenOrientation="portrait" 添加到清单文件中,但这没有区别。

无论应用程序旋转如何,如何使黑条保持在屏幕的顶部和底部边缘?

标签: javaandroidandroid-studioandroid-11

解决方案


我认为您可以像这样简单地尝试重新签名您的activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:background="@android:color/background_dark"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:background="@android:color/holo_blue_dark">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="HELLO WORLD"
            android:textAlignment="center"
            android:textColor="#000000"
            android:textSize="28sp"
            android:textStyle="bold" />
    </LinearLayout>


</LinearLayout>

推荐阅读