如何从 XML 膨胀视图子类



我目前正在使用从 XML 膨胀的视图填充启动时Adapter

private void addView(Context context) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.deal_tile, this, null);
    mViews.add(view);
}

但是,我发现将视图存储在AdapterView内的列表中会产生这些视图中的控件问题,因此我想改为使用 Adapter#getView(int position, View recycle, ViewGroup container) 中的回收函数。

出于这个原因,我想使用自定义视图类,以便在适配器中重新填充它之前进行健全性检查(if(recycle!=null && recycle instanceof CustomView))。 但是,我无法找到您如何从 XML 膨胀自定义视图类。 我可以找出如何将膨胀视图添加到自定义视图,我可以了解如何将自定义视图插入 XML 布局等,显然我很乐意直接使用 LayoutInflater 膨胀这些东西,但我找不到生成自定义视图本身的等效项。 我想重用我已经拥有的 XML;因此,我不想直接对元素(以及它们的外观)进行编程。

我用它来创建自己的幻灯片库,我认为它会有所帮助。

    LinearLayout internalWrapper = new LinearLayout(getContext());
    internalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    internalWrapper.setOrientation(LinearLayout.HORIZONTAL);
    addView(internalWrapper);
    this.mItems = items;
    LinearLayout generalLayout = new LinearLayout(this.getContext());
    generalLayout = (LinearLayout) View.inflate(this.getContext(), R.layout.galleryrow, null);
    // inside linear layout
    LinearLayout generalLinear = (LinearLayout) generalLayout.findViewById(R.id.rowgenerallin);
    // set height & width to the LINEAR
    generalLinear.setLayoutParams(new LayoutParams(reference_width, reference_height));
    ImageView ivl = (ImageView) generalLayout.findViewById(R.id.arrow_left);
    ImageView ivr = (ImageView) generalLayout.findViewById(R.id.arrow_right);
    internalWrapper.addView(generalLayout);

就我而言,R.layout.gallery_row包含我要管理的两个图像,由LinearLayous (rowgenerllin)嵌套,内部包装器是在活动主布局中声明的空LinearLayout。仔细检查LayoutParams代码,否则你会得到一个大的空:)

干杯!

最新更新