Android 为什么此应用程序会因运行时错误而崩溃?
我有一个android项目,主要是来自android studio的模板应用程序。以下是Android 为什么此应用程序会因运行时错误而崩溃?,android,xml,android-activity,Android,Xml,Android Activity,我有一个android项目,主要是来自android studio的模板应用程序。以下是活动\u main.xml: <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_par
活动\u main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/gameStartButton"
android:text="Start"
android:fontFamily="serif"
android:textSize="30sp"
android:textColor="@color/colorAccent"
android:background="@color/colorPrimaryDark"
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="@string/mainMenuItemWidth"/>
</android.support.constraint.ConstraintLayout>
当我启动此应用程序时,它会因以下回溯而崩溃:
08-26 17:57:36.256 5868-5868/com.example.saga.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.saga.test, PID: 5868
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.saga.test/com.example.saga.test.MainActivity}: java.lang.RuntimeException: Binary XML file line #0: You must supply a layout_height attribute.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2534)
如您所见,我实际上为约束布局和按钮提供了一个
layout\u height
属性,那么为什么会出现此错误?您不能将字符串值用于layout\u height。将该值放入dimens.xml中,并使用
android:layout_height="@dimen/mainMenuItemWidth"
根本原因:您正在使用字符串作为属性
android:layout\u height
。预期值为整数
或dimen
值
解决方案:在res/values
文件夹中创建一个名为dimens.xml
的新文件,然后将下面的部分添加到其中
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="mainMenuItemWidth">20dp</dimen>
</resources>
20dp
然后在xml文件中
<Button
android:id="@+id/gameStartButton"
android:text="Start"
android:fontFamily="serif"
android:textSize="30sp"
android:textColor="@color/colorAccent"
android:background="@color/colorPrimaryDark"
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="@dimen/mainMenuItemWidth"/>
由于android:layout\u height=“@string/mainMenuItemWidth”,应用程序崩溃,因为
layout\u height
不是接受字符串类型的值
在dimen
文件中创建一个名为mainMenuItemWidth
将android:layout\u height=“@string/mainMenuItemWidth”
更改为android:layout\u height=“@dimen/mainMenuItemWidth”
我希望它对您有用。它告诉您哪种是解决方案:
您必须提供布局高度属性。
<Button
android:id="@+id/gameStartButton"
android:text="Start"
android:fontFamily="serif"
android:textSize="30sp"
android:textColor="@color/colorAccent"
android:background="@color/colorPrimaryDark"
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="@dimen/mainMenuItemWidth"/>