【问题标题】:Can't access elements from custom view无法从自定义视图访问元素
【发布时间】:2018-07-14 20:36:29
【问题描述】:

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

<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>

我有以下类,我试图通过以下方式访问 txtTitle 元素:

public class CustomLinearLayout extends LinearLayout 
{
    public CustomLinearLayout( Context context, AttributeSet attrs ) 
    {
        super( context, attrs );

        TextView txtTitle = (TextView)findViewById( R.id.txtTitle );
    }
}

但 txtTitle 始终为空。我也尝试像这样访问它,但没有任何运气:

    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?谢谢!

【问题讨论】:

标签: java android layout


【解决方案1】:

您无法在 Constructor() 期间访问子项,因为它们尚未加载并从 XML 中读取。 LinearLayout.Constructor() 是解析 XML 时调用的第一个方法,并且只有在它读取/解析所有子级之后,因此在 Constructor() 期间它们不可访问/可见/ready_to_use。

请使用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多