代码之家  ›  专栏  ›  技术社区  ›  Kristian

无法从自定义视图访问元素

  •  0
  • Kristian  · 技术社区  · 7 年前

    我有一个自定义的线性布局。它包含一个文本框和一些其他元素。

    <a.b.c.CustomLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    >
        <TextView
        android:id="@+id/txtTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18dp"
        />
    </a.b.c.CustomLinearLayout>
    

    我有以下类,从中我尝试以下方式访问txtitle元素:

    public class CustomLinearLayout extends LinearLayout 
    {
        public CustomLinearLayout( Context context, AttributeSet attrs ) 
        {
            super( context, attrs );
    
            TextView txtTitle = (TextView)findViewById( R.id.txtTitle );
        }
    }
    

    但是txtitle总是空的。我也试着这样访问它,但没有任何运气:

        TextView txtTitle = (TextView)this.findViewById( R.id.txtTitle );
        TextView txtTitle = (TextView)((Activity)context).findViewById( R.id.txtTitle );
        TextView txtTitle = (TextView)context.findViewById( R.id.txtTitle );
    

    如何从上下文访问TextView?谢谢您!

    1 回复  |  直到 7 年前
        1
  •  1
  •   emandt    7 年前

    您不能在构造函数()期间访问子级,因为它们尚未加载并从XML中读取。linearlayout.constructor()是解析XML时调用的第一个方法,只有在它之后才能读取/解析所有子级,因此在constructor()期间,它们不可访问/可见/准备使用。

    请使用:

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }