
本文详解 Android 自定义视图中 TextView 不显示的根本原因(getWidth()/getHeight() 为 0)及解决方案,重点说明 ViewGroup 的布局生命周期、onLayout 正确用法与 doOnLayout 的关键作用。
本文详解 android 自定义视图中 textview 不显示的根本原因(`getwidth()`/`getheight()` 为 0)及解决方案,重点说明 `viewgroup` 的布局生命周期、`onlayout` 正确用法与 `doonlayout` 的关键作用。
在 Android 开发中,当继承 RelativeLayout 并动态添加 TextView 却无法显示时,往往并非 UI 层面的样式问题,而是布局测量与定位时机错误所致。您遇到的核心现象——getWidth() 和 getHeight() 返回 0、X/Y 坐标有值但 TextView 不可见——正是典型的“在尺寸未确定前强行设置位置”的结果。
❌ 原代码的问题分析
错误继承 RelativeLayout:RelativeLayout 是一个完整功能的布局容器,它自身已实现 onMeasure() 和 onLayout()。您重写 onLayout() 却未调用 super.onLayout(),且在其中反复 removeView()/addView(),破坏了布局流程;更严重的是,在 dispatchDraw() 中读取 getWidth()/getHeight() ——此时测量阶段早已结束,但若父容器尚未完成布局(如 ConstraintLayout 中未触发最终测量),这些值仍为 0。
dispatchDraw() 不是设置位置的时机:该方法用于绘制阶段,此时视图尺寸虽已确定,但 TextView 尚未被 addView() 添加到层级树中(您的 init() 只创建了实例,未添加),导致 setLayoutParams() 无效,且 setX()/setY() 在 LayoutParams 未生效时属于“手动偏移”,易被后续布局覆盖。
-
onLayout() 实现不合规:ViewGroup 的 onLayout() 必须显式调用子视图的 layout(l, t, r, b) 来指定其确切区域。仅 addView() 不足以触发布局,且 removeView()/addView() 在 onLayout() 中调用会引发无限递归或布局紊乱。
✅ 正确解法:改用 ViewGroup + 合理生命周期管理
ViewGroup 是所有布局容器的基类,它强制开发者实现 onMeasure() 和 onLayout(),从而彻底掌控子视图的尺寸与位置逻辑。以下是推荐实现:
public class MyView extends ViewGroup {
private TextView nrText;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyView(Context context) {
super(context);
init(context);
}
private void init(Context context) {
nrText = new TextView(context);
// 设置 LayoutParams(必须!否则 addView 失效)
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
nrText.setLayoutParams(lp);
nrText.setTextColor(Color.WHITE);
nrText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 70); // 推荐使用 SP 单位
nrText.setText("Hello"); // 别忘了设置文本内容!
// 关键:在视图完成首次布局后,再设置绝对坐标
nrText.doOnLayout(() -> {
// 此时 getWidth()/getHeight() 已可靠
float centerX = getWidth() / 2f - nrText.getWidth() / 2f;
float centerY = getHeight() / 2f - nrText.getHeight() / 2f;
nrText.setTranslationX(centerX);
nrText.setTranslationY(centerY);
});
addView(nrText); // 立即添加到 ViewGroup
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 测量自身:至少包裹子视图(可按需调整)
measureChildren(widthMeasureSpec, heightMeasureSpec);
int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// ViewGroup 必须实现此方法:为每个子视图调用 layout()
// 由于我们只有一子视图且用 translation 定位,此处可留空或做基础布局
// 注意:translation 不影响 layout() 调用,但需确保子视图已存在
if (nrText != null && nrText.getParent() == this) {
// 确保子视图占满父容器(供 translation 基准)
nrText.layout(0, 0, getMeasuredWidth(), getMeasuredHeight());
}
}
}
⚠️ 关键注意事项
- doOnLayout() 是黄金法则:它会在视图首次完成 onLayout() 后回调,此时 getWidth()/getHeight() 绝对可靠,避免了竞态条件。
- setTranslationX/Y 优于 setX/Y:setX() 是 left + translationX 的合成值,而 translationX 更适合动态偏移,且不会干扰 LayoutParams。
- 务必调用 setText():TextView 默认无内容,即使尺寸正确也不会渲染。
- XML 中无需额外属性:您的 ConstraintLayout 使用 match_parent 即可,layout_weight 对 ViewGroup 无效,应移除。
- 避免在 Fragment 中操作内部 View:v.nrText.setWidth(100) 违反封装原则,且此时 nrText 尚未测量,无效。所有 UI 逻辑应封装在 MyView 内部。
✅ 验证效果
运行后,TextView 将稳定居中显示。日志中 v.nrText.getWidth() 将输出非零值,证明测量已成功完成。
通过回归 ViewGroup 基础并严格遵循 Android 布局生命周期(measure → layout → draw),您不仅能解决当前问题,更能构建出可预测、易维护的自定义视图组件。











