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

あなたの 2 つの XML レイアウトに混乱しています。

2 つ目は、ウィジェットを使用する場所です。ClearableCaptionedButtonしたがって、名前の付いたクラスが package にあると想定していますde.pockettaxi.widget

さらに、最初のレイアウトに表示されている とは、 の再利用者によって提供されるものではなく、常に にあるはずのものであると想定していButtonます。ImageViewClearableCaptionButtonClearableCaptionButton

これらの仮定がすべて正しい場合、2 つの問題があります。

  • まず、私が見ることができるどこでも最初のレイアウトを使用していません。
  • 第 2 に、最初のレイアウトにはmyapp.widget.ClearableCaptionedButtonおそらく存在しない への参照があります。

myapp.widget.ClearableCaptionedButton要素を要素に置き換えてから、コンストラクターまたはof<merge>でそのレイアウトを膨らませます。onFinishInflate()ClearableCaptionedButton

これは、この方法で動作するカスタム ウィジェットの使用法を示す、私の本の 1つからのサンプル プロジェクトです。

また、パッケージ名を考えると、それが非常に大きなポケットまたは非常に小さなタクシーのいずれかであることを願っています... :-)

于 2010-06-12T13:14:05.370 に答える