0

我正在尝试使用多个提要项目实现新闻提要类型的布局。新闻源项目在折叠时将具有特定布局,并且当单击该项目时,此布局将被“展开”版本替换。

我通过使用自定义项目的 ListView 实现了这一点。自定义项 XML 布局文件有一个 ViewStub,这是我用来来回更改布局的。不过,现在我想将布局“迁移”到 RecyclerView,并遵循 ViewHolder 设计模式。后者是我首先尝试的,我遇到了各种各样的问题。

我的方法如下:

  1. 获取折叠布局(events_list_item_content)和展开布局(events_list_item_selected_content)的参考;

  2. 获取对要设置为 ViewStub 布局 (view_stub_layout) 的简单布局资源文件的引用。

  3. 获取 ViewStub 引用,设置其布局 (view_stub_layout) 膨胀,并将折叠的布局视图添加到此布局(第一次创建提要时,它的所有项目都将被折叠)。

  4. (初始化后,单击项目时)从 ViewStubLayout 中删除上一个视图(布局),添加其他类型的布局。

这是我的自定义适配器类:

public class FeedRecyclerAdapter extends BaseAdapter {


public class ViewHolder {
    View inflatedViewStub1;  
    ViewStub viewStub;
    LinearLayout  viewStubLayout;
    LinearLayout listItemContent, listItemContentSelected;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final FeedItem item = feedItems.get(position);
    final ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = inflater.inflate(R.layout.events_list_item_content_new_container, parent, false);
        View view = null;

        view = inflater.inflate(R.layout.events_list_item_content, null);
        viewHolder.listItemContent = (LinearLayout) view.findViewById(R.id.events_list_item_content);

        view = inflater.inflate(R.layout.events_list_item_selected_content, null);
        viewHolder.listItemContentSelected = (LinearLayout) view.findViewById(R.id.events_list_item_content_selected);

        view = inflater.inflate(R.layout.view_stub_layout, null);
        viewHolder.viewStubLayout = (LinearLayout) view.findViewById(R.id.view_stub_layout);

        viewHolder.viewStub = (ViewStub) convertView.findViewById(R.id.list_item_feed);           

 (viewHolder.viewStubLayout).addView(viewHolder.listItemContent);
        viewHolder.viewStub.setLayoutResource(R.layout.view_stub_layout);
        viewHolder.inflatedViewStub1 = viewHolder.viewStub.inflate();
        convertView.setTag(viewHolder);

    } else viewHolder = (ViewHolder) convertView.getTag();
    if (item.getExploded()) {
        viewHolder.viewStubLayout.removeAllViews();
        viewHolder.viewStubLayout.addView(viewHolder.listItemContentSelected);
    } else {
        viewHolder.viewStubLayout.removeAllViews();
        viewHolder.viewStubLayout.addView(viewHolder.listItemContent);
    }
  return convertView;
  }

但是,在测试时,Newsfeed 应该出现的页面是空白的。

4

1 回答 1

0
ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
stub.setLayoutResource(layoutId);
stub.inflate(); // inflate 1st layout

ll.removeAllViews(); // remove previous view, add 2nd layout
ll.addView(LayoutInflater.from(context).inflate(secondLayoutId, ll, false));

Android ViewStub 以编程方式更改布局

于 2016-09-10T21:57:48.870 回答