我用 XML 制作了一个自定义组件,由一个按钮和一个 ImageView 组成:
<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
}
我的问题类似于this一。当我尝试在自定义化合物中查找 View 时,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>
有人能发现什么吗?谢谢。
最佳答案
我对你的两个 XML 布局感到困惑。
第二个是你说你使用小部件的地方。因此,我假设名为 ClearableCaptionedButton
的类在包裹里de.pockettaxi.widget
.
我进一步假设 Button
和 ImageView
在您的第一个布局中显示的是始终应该在 ClearableCaptionButton
中的东西,不是 ClearableCaptionButton
的重用者提供的东西.
如果这些假设都是正确的,那么你有两个问题。
- 首先,您没有使用第一个 在我能看到的任何地方布局。
- 第二个,第一个
布局引用了
myapp.widget.ClearableCaptionedButton
那可能不存在。
我会替换 myapp.widget.ClearableCaptionedButton
带有 <merge>
的元素元素,然后在构造函数或 onFinishInflate()
中扩充该布局的 ClearableCaptionedButton
.
Here is a sample project来 self 的一本书,它展示了如何使用以这种方式工作的自定义小部件。
此外,鉴于您的包裹名称,我希望它是一个非常大的口袋或一辆非常小的出租车...:-)
关于Android - 自定义复合组件中的 View 未膨胀(findByView 返回 null),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3028332/