【发布时间】:2017-07-30 18:23:39
【问题描述】:
我是 Android 新手,在 Android Studio 中设计布局时遇到问题。我发现了许多相关的问题,但没有一个有效。 Android Studio 始终根据当前预览大小(Pixel、Nexus 7...)在 dp 中硬编码约束值。
我在 XML 编辑器中编写的代码(在我的手机上运行良好):
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.meanstreet.note.Slider
android:id="@+id/slider"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.meanstreet.note.MainActivity">
<RelativeLayout
android:id="@+id/menu"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/bold"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="@string/bold_button" />
...
在我进入“设计”标签后更改了代码(不适合我的手机屏幕):
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.meanstreet.note.Slider
android:id="@+id/slider"
android:layout_width="344dp"
android:layout_height="495dp"
tools:context="com.meanstreet.note.MainActivity"
tools:layout_editor_absoluteY="8dp"
tools:layout_editor_absoluteX="8dp">
<RelativeLayout
android:id="@+id/menu"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/bold"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="@string/bold_button" />
...
Slider 是扩展 RelativeLayout 的自定义视图。
Slider 中的硬编码值取决于 Android Studio 中用于预览的所选手机,并且该视图现在不在我的手机中(如果所选手机更大)或右侧和底部的边距很大(如果所选手机更小)。
这对我来说似乎很奇怪:我仍然可以避免进入“设计”选项卡,这样代码就不会被更改并且可以在任何设备上运行,但这很烦人。
为什么 Android Studio 会这样?我怎样才能让宽度和高度保持在“match_parent”,从而在任何手机上都有正确的尺寸?
提前感谢您的帮助。
【问题讨论】:
-
"我发现了很多相关的问题,但没有一个有效。"您发现了哪些相关问题?当您尝试建议的解决方案时,结果如何?您想要的结果与这些结果有何不同?
-
"我怎样才能让宽度和高度保持在 "match_parent" 上?"只需将宽度和高度设置为“match_parent”即可。
-
stackoverflow.com/questions/37505641/… => 说值不是在代码中编译的,但似乎是。 stackoverflow.com/questions/40126678/… => 使用 0dp,滑块不显示。 stackoverflow.com/questions/43452384/… => 我尝试推断常量,但结果更糟,插入了屏幕一半大小的边距
-
@Code-Apprentice 我一进入“设计”选项卡,这些值就会被 dp 中的值替换,如我发布的代码所示:这就是问题所在
-
嗯,它试图让你使用约束,因为这就是布局的目的。如果这是问题,欢迎您更改任何您想要的约束布局
标签: android android-layout android-studio android-constraintlayout