Android - Views in custom composite component are not inflated (findByView returns null)

I created a custom component in XML consisting of a button with an image stacked on top of it:

<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 source code extraction:

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
}

My problem is similar to this . When I try to find views inside a custom connection, findViewById returns null. But, as you can see, I already added super (context, attrs); to the constructor. I use a custom component directly in the xml layout, for example:

<LinearLayout>
<!-- some stuff -->
<myapp.widget.ClearableCaptionedButton
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    app:caption="to"/>
</LinearLayout>

Can anyone notice something? thank.

+3
source share
1 answer

I am confused by your two XML layouts.

-, , . , , ClearableCaptionedButton de.pockettaxi.widget.

, Button ImageView, , - , ClearableCaptionButton, -, ClearableCaptionButton.

, .

  • .
  • -, layout myapp.widget.ClearableCaptionedButton, , , .

myapp.widget.ClearableCaptionedButton <merge>, onFinishInflate() ClearableCaptionedButton.

, , .

, , , , ...: -)

+6

Source: https://habr.com/ru/post/1749726/


All Articles