3

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

有人能发现什么吗?谢谢。

4

1 回答 1

6

我对你的两个 XML 布局感到困惑。

第二个是你说你使用小部件的地方。因此,我假设名为的类ClearableCaptionedButton在 package 中de.pockettaxi.widget

我进一步假设您的第一个布局中显示的ButtonImageView是始终应该包含在 中的ClearableCaptionButton东西,而不是由 的重用者提供的东西ClearableCaptionButton

如果这些假设都是正确的,那么你有两个问题。

  • 首先,您没有在我能看到的任何地方使用第一个布局。
  • 其次,第一个布局引用了myapp.widget.ClearableCaptionedButton可能不存在的 a。

我会myapp.widget.ClearableCaptionedButton用一个元素替换该元素,<merge>然后在构造函数或onFinishInflate().ClearableCaptionedButton

这是我的一本书中的一个示例项目,它显示了以这种方式工作的自定义小部件的使用。

另外,鉴于您的包裹名称,我希望它是一个非常大的口袋或非常小的出租车...... :-)

于 2010-06-12T13:14:05.370 回答