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

Android Studio中自定义RelativeLayout内TextView不显示问题求助

自定义RelativeLayout子类中TextView无法显示且宽高为0的问题

我自定义了继承RelativeLayout的MyView,尝试添加名为nrText的TextView,但该TextView无法显示。在主Fragment中将MyView添加到布局后,用Log.d打印MyView的getX()、getWidth()和getHeight(),发现getX()有实际数值,但getWidth()和getHeight()均为0。


MyView类代码

package com.example.myapplication2.ViewModels;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MyView extends RelativeLayout{
    private TextView nrText;
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyView(Context context) {
        super(context);
        init(context);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);

        nrText.setLayoutParams(lp2);
        nrText.setTextColor(Color.WHITE);
        nrText.setTextSize(70);
        nrText.setX(getWidth()/2f);
        nrText.setY(getHeight()/2f);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        removeView(nrText);
        addView(nrText);
    }

    private void init(Context context){
        nrText = new TextView(context);
    }
}

尝试过的修改

曾尝试将以下代码:

RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
nrText.setLayoutParams(lp2);

替换为:

nrText.setWidth(100);
nrText.setHeight(100);

但没有任何变化。


Fragment代码

public class Start4 extends Fragment {

    private MyView v;
 
    // 注:原代码中这段代码直接写在类中,会导致空指针,位置错误
    v.nrText.setWidth(100);

    v.nrText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Log.d("sdad",String.valueOf(v.nrText.getX() + " " + v.nrText.getHeight()));
        }
    });    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.st4, container, false);
        v=view.findViewById(R.id.ss);

        return view;
    }
}

XML布局代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
   android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.myapplication2.ViewModels.MyView
    android:id="@+id/ss"
    tools:context=".StartModels.StartMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    />

</androidx.constraintlayout.widget.ConstraintLayout>

日志输出

D/sdad: 540.0 0
D/sdad: 540.0 0
D/sdad: 540.0 0
D/sdad: 540.0 0
D/sdad: 540.0 0
D/sdad: 540.0 0

问题原因分析

  1. onLayout方法的错误操作:在onLayout中反复执行removeView(nrText)和addView(nrText),会导致TextView被频繁移除添加,破坏View的测量布局流程,无法正常渲染。
  2. dispatchDraw中设置布局参数时机错误:dispatchDraw属于绘制阶段,此时View的测量布局已完成,在这里设置LayoutParams和位置会干扰正常流程,且getWidth()/getHeight()可能因之前的布局异常无法获取正确值。
  3. Fragment代码位置错误:直接在类中操作v.nrText会导致空指针,因为v还未初始化,代码需放在onCreateView之后的生命周期方法中。

修复方案

修改MyView类

package com.example.myapplication2.ViewModels;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MyView extends RelativeLayout{
    public TextView nrText; // 修改为public,方便Fragment访问,或提供getter方法

    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);
        // 初始化布局参数,设置居中
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        lp.addRule(CENTER_IN_PARENT, TRUE);
        
        nrText.setLayoutParams(lp);
        nrText.setTextColor(Color.WHITE);
        nrText.setTextSize(70);
        // 一次性添加到布局,无需反复操作
        addView(nrText);
    }
}

修改Fragment代码

public class Start4 extends Fragment {

    private MyView v;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.st4, container, false);
        v = view.findViewById(R.id.ss);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (v != null && v.nrText != null) {
            v.nrText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    // 移除监听避免重复回调
                    v.nrText.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    Log.d("sdad", v.nrText.getX() + " " + v.nrText.getHeight());
                }
            });
        }
    }
}

关键说明

  • 将TextView的初始化和添加操作放在init方法中,一次性完成,避免破坏布局流程。
  • 使用RelativeLayout的布局规则设置居中,比手动设置X/Y更符合Android布局机制。
  • Fragment中操作View的代码必须放在onViewCreated或之后的生命周期方法中,确保View已初始化完成。
  • 添加布局监听后记得移除,避免多次回调。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:55:01