【发布时间】: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?谢谢!
【问题讨论】:
-
看看这里的答案stackoverflow.com/questions/24697405/… 我认为你必须先放大你的视图才能访问其中的组件
-
@TylerV 感谢您的回复。这就是我不明白的,因为我在xml中定义了项目,它不是已经“膨胀”了还是我还需要膨胀它?
-
我不确定(我以前从未制作过自定义 LinearLayout),但查看此处的 LinearLayout 源代码 (android.googlesource.com/platform/frameworks/base/+/master/core/…) 和 ViewGroup 代码我没有看到任何夸大布局的东西.
-
看看这里stackoverflow.com/a/15493591/9473786 并尝试在
onFinishInflate中获取视图