为什么此应用程序因运行时错误而崩溃?

问题描述 投票:0回答:2

我有一个Android项目,主要是android studio的模板应用程序。这是activity_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>

这是MainActivity.java:package com.example.saga.test;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

当我启动这个应用程序时,它会与此追溯崩溃:

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_height属性,为什么我会收到此错误?

android xml android-activity
2个回答
1
投票

您不能为layout_height使用字符串值。将值放在dimens.xml中并使用引用该值

android:layout_height="@dimen/mainMenuItemWidth"

1
投票

根本原因:您正在使用属性android:layout_height的字符串。预期是integerdimen值。

解决方案:在名为res/valuesdimens.xml文件夹中创建一个新文件,然后在其中添加以下部分。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="mainMenuItemWidth">20dp</dimen>
</resources>

然后在你的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"/>
© www.soinside.com 2019 - 2024. All rights reserved.