【问题标题】:How can I inflate a View subclass from XML?如何从 XML 扩展视图子类?
【发布时间】:2012-11-19 12:29:40
【问题描述】:

我目前正在使用从 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;因此,我不想直接对元素(以及它们的外观)进行编程。

【问题讨论】:

  • 顺便说一句,如果这个问题不是重复的东西,我会感到惊讶,但我已经浏览了大约 20 个问题,它们似乎都略有不同。我认为关于“通货膨胀”和“自定义视图”的问题可能需要系统重新命名。
  • 我想知道你是否可以去XmlPullParser parser = context.getResources().getXml(R.layout.deal_tile); AttributeSet attributes = Xml.asAttributeSet(parser); View view = new CustomView(context, attributes); 还是会很麻烦?
  • 我通常会像这样进行健全性检查:if (recycle == null || recycle.getId() != R.layout.deal_tile)。如果计算结果为true,则需要再次膨胀布局。
  • 仍然对最初的问题感到好奇,但它确实解决了我的直接问题。

标签: android xml view subclass inflate


【解决方案1】:

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

    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 代码,否则你会得到一个很大的 NULL :)

干杯!

【讨论】:

  • 是的,正如我所说,我正在使用这件作品来创造另一件东西,只需少用一个 LinearLayout 来推断它。
  • 这就是我目前的做法;不过,我需要能够使用相同的布局文件(理想情况下)创建View 的子类,这样我就可以在Adapter#getView(int pos, View recycle, ViewGroup ctr) 中使用回收的视图参数
  • 所以下一步可能是实现适配器的getView()方法的初始化逻辑来加载自定义布局或者回收它,听起来很有趣!
  • 我已经做到了。我想将自定义 XML 放入自定义视图类中,这样我就可以简单地重新填充各种字段,因为我知道已为我提供了正确的视图类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 2013-08-06
  • 2011-11-27
  • 1970-01-01
相关资源
最近更新 更多