将java类连接到包含的xml android

将java类连接到包含的xml android,android,view,include,Android,View,Include,我有一个xml布局,其中包含我多次使用的元素。。。所以我决定在xml中使用,以避免多余的代码。 我的问题是,我想创建一个连接到这个包含的xml组件并引用它的类,而不是多次编写相同的代码 我试图阅读自定义视图组件,并创建了一个类ParcelPopbarView: public ParcelTopBarView extends View { /... public ParcelTopBarView(Context context, ParcelListItem parcelListItem) {

我有一个xml布局,其中包含我多次使用的元素。。。所以我决定在xml中使用
,以避免多余的代码。 我的问题是,我想创建一个连接到这个包含的xml组件并引用它的类,而不是多次编写相同的代码

我试图阅读自定义视图组件,并创建了一个类ParcelPopbarView:

public ParcelTopBarView extends View {

/...

public ParcelTopBarView(Context context, ParcelListItem parcelListItem) {
        super(context);
        this.parcelListItem = parcelListItem;
        this.context = context;

        titleTextView = findViewById(R.id.title_textview);
        subtitleTextView = findViewById(R.id.subtitle_textview);
        deliveryInfoTextView = findViewById(R.id.delivery_info_textview);
        thumbnailLogo = findViewById(R.id.thumbnail_logo);

    }

    public void setTopbar(){
      titleTextView.setText("hello!");  
    }
但我觉得自定义视图主要是关于在画布上绘制的,我没有这样做。。。所以我也不知道使用view是否正确。 无论如何,titleTextView都是空的,因为它找不到xml文件的引用,我不知道如何引用它


有没有人有一个聪明的解决方案来帮助我以正确的方式做到这一点

您需要为自定义视图的所有构造函数膨胀布局,以便以后能够访问它们

public class ParcelTopBarView extends View {

public ParcelTopBarView(Context context) {
    super(context);
    init();
}

public ParcelTopBarView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init();
}

public ParcelTopBarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

public ParcelTopBarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init();
}


private void init() {
    View view = inflate(getContext(), R.layout.parcel_top_bar, this);

    titleTextView = findViewById(R.id.title_textview);
    subtitleTextView = findViewById(R.id.subtitle_textview);
    deliveryInfoTextView = findViewById(R.id.delivery_info_textview);
    thumbnailLogo = findViewById(R.id.thumbnail_logo);
}