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

Android报错:LinearLayout无法转换为TextView,高分榜Dialog实现求助

解决Android自定义高分榜Dialog的类型转换异常问题

嘿,我来帮你搞定这个问题!你遇到的android.widget.LinearLayout cannot be cast to android.widget.TextView异常,主要有两个核心原因,咱们一步步解决:

1. 先修复XML布局的致命错误

你的row_key.xml和row_value.xml写法存在问题:TextView是单一控件,无法容纳子View,但你在TextView标签里嵌套了<include>标签,这会导致Android系统解析布局时,自动把TextView包裹在一个LinearLayout里(因为TextView没法承载子View),所以你inflate出来的根布局实际是LinearLayout,强转成TextView肯定报错。更糟的是,两个布局互相include还会造成无限递归加载,这绝对不行!

咱们把这两个布局改成独立的TextView布局,去掉互相嵌套的include:

修改后的row_key.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="dummy_text"
    android:id="@+id/row_textView_key"
    android:layout_marginTop="20sp"
    android:textStyle="bold"
    android:textSize="30sp"
    android:layout_marginLeft="20sp"/>

修改后的row_value.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="dummy_value"
    android:id="@+id/row_textView_value"
    android:layout_marginTop="5sp"
    android:layout_marginLeft="20sp"
    android:textSize="30sp"/>

2. 初始化Dialog里的LinearLayout变量

你的layout变量一直是null,因为构造函数里没找到对应的LinearLayout实例,得补上这行初始化代码:

public CustonDialog(Context context) {
    super(context, android.R.style.Theme_Translucent_NoTitleBar);
    setContentView(R.layout.activity_highscore);
    setCancelable(false);
    mContext = context;
    // 初始化layout变量,绑定到布局里的LinearLayout
    layout = findViewById(R.id.linear_layout);
    Button buttonClose = (Button) findViewById(R.id.button_close);
    buttonClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dismiss();
        }
    });
}

3. 修正addKeyValuePair方法的代码

之前你直接把inflate出来的View强转成TextView,现在布局改对了,咱们要正确获取TextView实例:

public void addKeyValuePair(String key, String value) {
    // 加载row_key布局,获取对应的TextView
    View keyView = getLayoutInflater().inflate(R.layout.row_key, layout, false);
    TextView textView_key = keyView.findViewById(R.id.row_textView_key);
    // 加载row_value布局,获取对应的TextView
    View valueView = getLayoutInflater().inflate(R.layout.row_value, layout, false);
    TextView textView_value = valueView.findViewById(R.id.row_textView_value);
    
    textView_key.setText(key);
    textView_value.setText(value);
    
    layout.addView(keyView);
    layout.addView(valueView);
}

另外,建议你把类名CustonDialog改成CustomDialog,拼写更准确哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:37:10