Kotlin Android:如何为Chrome OS设置应用窗口大小
Hey there! Let's get your app launching at a fixed 1/4 screen size on Chrome OS. You're right that match_parent in your layout makes content fill the available window, but the real issue is controlling the initial window dimensions that Chrome OS assigns to your Android app. Here's how to solve this properly:
Step 1: Enable Resizable Activity (Critical for Chrome OS)
First, make sure your app supports resizable windows in Chrome OS. Open your AndroidManifest.xml and add the resizeableActivity attribute to your <activity> tag (or <application> tag to apply to all activities):
<activity android:name=".YourMainActivity" android:resizeableActivity="true"> <!-- other attributes like intent filters --> </activity>
This tells Chrome OS that your app can adjust its window size, which is a prerequisite for setting custom dimensions.
Step 2: Set Window Size Programmatically in Your Activity
In your Kotlin Activity (e.g., MainActivity.kt), add code to calculate the screen size and set your desired window dimensions right after setting the content view. We'll target 1/4 of the screen area (which means width and height each set to half the screen size):
import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.your_main_layout) // Exit fullscreen mode if the app defaults to it window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE // Get screen metrics to calculate desired size val displayMetrics = resources.displayMetrics val screenWidth = displayMetrics.widthPixels val screenHeight = displayMetrics.heightPixels // Calculate 1/4 screen size (width/2 * height/2 = 1/4 total area) val targetWidth = screenWidth / 2 val targetHeight = screenHeight / 2 // Apply the new window dimensions val windowParams = window.attributes windowParams.width = targetWidth windowParams.height = targetHeight window.attributes = windowParams } }
Step 3: Keep Your Layout Flexible
You can leave your layout's layout_width and layout_height as match_parent—this will let your content fill the custom window size you've set. If you want content to be centered, add padding, or have specific spacing, adjust your ConstraintLayout with margins, gravity rules, or nested layouts as needed.
Why This Works
Chrome OS manages Android app windows separately from the layout content. Your match_parent layout just fills whatever window space the system gives it; by setting the window dimensions directly in code, you override the default fullscreen behavior and force the app to launch at your preferred size.
内容的提问来源于stack exchange,提问作者jv.m

