【问题标题】:find layout type of a view查找视图的布局类型
【发布时间】:2012-11-27 18:30:29
【问题描述】:

我有一个自定义的 ExpandableListAdapter,我在其中指定了 getGroup(...),如下所示:

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

    //do stuff
    if(something) {
        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.tasks_list_group_with_child, null);
        }

        TextView taskNameText = (TextView) convertView.findViewById(R.id.tlgwc_task_name);
        //do stuff


    } else {
        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.tasks_list_group_without_child, null);        
        }

        TextView taskNameText = (TextView) convertView.findViewById(R.id.tlgwoc_task_name);
        //do stuff

    }

    return convertView;
}

现在的问题是,当我更改在适配器中使用的数据时,getGroup(...) 方法的参数(被重用的视图对象)“convertView”可能不再具有正确的布局.如何检查它是具有 R.layout.tasks_list_group_without_child 还是 R.layout.tasks_list_group_with_child 布局的视图?

正如 API 所说的“convertView:如果可能的话,要重用的旧视图。您应该在使用前检查此视图是否为非空且类型合适”,但如何操作?!

【问题讨论】:

    标签: android layout view expandablelistadapter


    【解决方案1】:

    如果您使用 BaseExpandableListAdapter,您可以使用视图类型,因此在您的情况下,该组必须:
    - 覆盖 getGroupTypeCount 以返回 2 个或更多 (1)
    - 覆盖 getGroupType 为您需要的每个不同布局返回不同的数字 (2)
    - 然后在膨胀视图时调用 getGroupType 以了解视图的类型,如果 convertView 不为空,则其上的视图将是您想要的类型的视图,因为 android 使用它来跟踪不同类型的视图您定义并回收了您需要的相同类型的视图。

    【讨论】:

      【解决方案2】:

      您可以将标签附加到视图

      view.setTag( "TAG" );

      并从 convertView 中检索它。

      了解更多信息:here

      【讨论】:

        【解决方案3】:

        执行此操作的“正确”方法是使用 nininho 提到的 getGroupTypeCount 技术。但是,如果您想要一种快速而肮脏的方式来做到这一点,可以通过为 R.layout.tasks_list_group_with_child 和 R.layout.tasks_list_group_without_child 设置一个布局来实现相同的效果,但在一种情况下使某些元素消失而在另一种情况下可见。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-09
          • 2011-06-25
          • 2017-03-24
          • 1970-01-01
          • 1970-01-01
          • 2016-05-29
          • 2010-12-19
          • 2016-05-10
          相关资源
          最近更新 更多