将Java类连接到包含的xml android

问题描述 投票:0回答:1

我有一个使用多个元素的xml布局,因此我决定在xml中使用<include>以避免过多的代码。我的问题是我想创建一个连接到此包含的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!");  
    }

但是我觉得自定义视图主要是关于在画布上绘制,我没有这样做...所以我也不知道使用视图是否正确。无论哪种方式,titleTextView都为null,因为它无法找到对xml文件的引用,而且我也不知道如何引用它。

有人对我如何以正确的方式做到这一点有明智的解决方案吗?

我有一个XML布局,其中一个元素我多次使用...所以我决定在XML中使用以避免多余的代码。我的问题是我想建立一个与此类相关的类...

android view include
1个回答
0
投票

您需要为自定义视图的所有构造函数增加布局,以便以后可以访问它们。

© www.soinside.com 2019 - 2024. All rights reserved.