You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android新手求助:Java与XML代码异常排查

排查BMI计算器开发中的Java/XML异常问题

我是Android编程新手,开发BMI计算器时遇到问题,怀疑Java或XML代码存在异常。已尝试给XML布局添加android:id="main"属性,且布局文件名为activity_main.xml,但问题仍未解决,恳请帮助排查。

相关代码

Java代码

package com.daniel.bmicalculator;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }
}

XML布局代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/image_balance"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BMI CALCULATOR" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

</LinearLayout>

排查方向

  • 确认根布局id是否正确添加:你提到添加了android:id="main",但当前XML的根LinearLayout没有这个属性。正确写法是给根布局加上android:id="@+id/main",注意格式是@+id/前缀,否则Java代码中findViewById(R.id.main)会找不到控件,引发空指针异常。
  • 检查图片资源是否存在:XML中引用的@drawable/image_balance,请确认该图片文件存在于res/drawable目录,文件名大小写完全匹配(Android资源名区分大小写),缺失会导致布局加载失败。
  • 补全或清理空布局:当前XML里有一个空的水平LinearLayout,虽不会直接崩溃,但后续添加控件时可能出现布局混乱,建议要么补全内容要么删除该空布局。
  • 补充BMI计算逻辑:当前Java代码仅做了窗口适配,没有任何计算相关逻辑。如果是无法实现BMI计算功能,需要添加输入身高、体重的EditText,计算按钮,并给按钮设置点击事件,在事件中获取输入值、计算BMI并展示结果。

内容的提问来源于stack exchange,提问作者Farner3232

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 17:21:04