gpt4 book ai didi

java - 无法从自定义 View 访问元素

转载 作者:行者123 更新时间:2023-12-02 11:00:48 24 4
gpt4 key购买 nike

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

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

最佳答案

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

请使用:

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

关于java - 无法从自定义 View 访问元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51343195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com