Android - 自定义复合组件中的 View 未膨胀(findByView 返回 null)

标签 android android-relativelayout

我用 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 .

我进一步假设 ButtonImageView在您的第一个布局中显示的是始终应该在 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/

相关文章:

Android:语音气球 - ImageView 重叠父级

java - 如何动态添加某个元素下方的相对布局

java - 构建时 Android 访问被拒绝

java - 获取空对象引用如果我在第三个 Activity 之前启动第二个 Activity (如果我直接从第一个移动到第三个 Activity ,则没有错误)

java - 条形码扫描仪使用 ML Kit 仅读取 QR 码

Android/kindle 拖拽时偶尔卡顿

java - Android 和 java 蓝牙客户端服务器应用程序

android - VPN 的连接性没有变化?

android - 向动态 Android TextView 添加边距

android - 在 RelativeLayout 中垂直居中 TextView