首页 > 解决方案 > 我可以在 Android Studio 3.0 中设计自定义大小的活动吗?

问题描述

通常,活动将显示最大屏幕。我希望显示一个宽 400px 高 500px 的窗口,但是下面还是显示一个完整的窗口,为什么?

主要活动

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="400px"
        android:layout_height="500px"
        tools:context=".MainActivity">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World OK!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>

到克六月

谢谢!但是你的代码不起作用,运行你的代码后窗口是全屏的。

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val m = windowManager
        val d = m.defaultDisplay
        val p = window.attributes
        p.height = dp2px(this, 500f)
        p.width = dp2px(this, 400f)
        window.attributes = p

    }

    private fun dp2px(context: Context, dp: Float): Int {
        val scale = context.getResources().getDisplayMetrics().density
        return (dp * scale + 0.5f).toInt()
    }

}

标签: android

解决方案


为了实现您想要的,您只需将以下内容添加到您的应用程序主题中:

<!-- Your application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

    <!-- Your arguments -->
    <item name="android:windowIsFloating">true</item>
</style>

文档中:

指示这是否是浮动窗口的标志。可能是一个布尔值,例如“true”或“false”。

这意味着您的活动将以您想要的大小放置在屏幕上。检查上面的演示以获取我创建的测试应用程序。

演示

带有 windowIsFloating 的应用程序


有关如何实施的更多信息,请查看此 StackOverflow 答案:https ://stackoverflow.com/a/12275009/1574250


推荐阅读