我在 XML 中制作了一个自定义组件,其中包含一个顶部堆叠有图像视图的按钮:
<myapp.widget.ClearableCaptionedButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/ccbutton_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|left"
android:textAppearance="?android:attr/textAppearanceMedium"
android:background="@android:drawable/edit_text"/>
<ImageView
android:id="@+id/ccbutton_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dip"
android:layout_alignRight="@id/ccbutton_button"
android:layout_alignTop="@id/ccbutton_button"
android:layout_alignBottom="@id/ccbutton_button"/>
</myapp.widget.ClearableCaptionedButton>
java源代码摘录:
public class ClearableCaptionedButton extends RelativeLayout implements OnClickListener {
...
public ClearableCaptionedButton(Context context, AttributeSet attrs) {
super(context, attrs);
// some stuff that works fine
}
..
protected void onFinishInflate() {
super.onFinishInflate();
mButton = (Button) findViewById(R.id.ccbutton_button);
mClear = (ImageView) findViewById(R.id.ccbutton_clear);
mButton.setText(""); // error here: mButton == null
}
我的问题与此类似。当我尝试在自定义化合物中查找视图时,findViewById 返回 null。但是,如您所见,我已经添加了 super(context, attrs); 给构造函数。我在 xml 布局中直接使用自定义组件,如下所示:
<LinearLayout>
<!-- some stuff -->
<myapp.widget.ClearableCaptionedButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
app:caption="to"/>
</LinearLayout>
有人能发现什么吗?谢谢。