0

我有以下活动层次结构:

public abstract class Base extends Activity {/* common stuff */}
public abstract class Middle extends Base {/* more common stuff */}
public class MyAppActivity extends Middle {/* the app */}

抽象的活动覆盖setContentView()并将给定的布局放入他们自己的布局中,如下所示:

/* Middle activity */
@Override
public void setContentView(int _layoutResID) {
  RelativeLayout middleLayout;
  ViewStub       stub;

  // Inflate middle layout
  middleLayout = (RelativeLayout)
    this.getLayoutInflater().inflate(R.layout.layout_middle, null);
  stub         = (ViewStub)
    middleLayout.findViewById(R.id.mid_content_stub);

  // Inflate content in viewstub.
  stub.setLayoutResource(_layoutResID);
  stub.inflate();

  // calls Base.setContentView(View)
  super.setContentView(middleLayout); 
}

如您所见,我使用它ViewStubs来避免生成的布局中容器视图的无用和膨胀层次结构。我想在抽象Base活动中做同样的事情,但因为我必须调用setContentView(View)(注意参数类型),所以我需要覆盖那个。不幸的是,似乎没有办法将 ViewStub 与视图一起使用。所以我想我必须像这样替换它:

/* Base activity */
@Override
public void setContentView(View _view) {
  RelativeLayout baseLayout;
  ViewStub       stub;

  baseLayout = (RelativeLayout)
    this.getLayoutInflater().inflate(R.layout.layout_base, null);
  stub       = (ViewStub)
    baseLayout.findViewById(R.id.base_content_stub);

  // Replace viewstub with content.
  baseLayout.removeView(stub);
  baseLayout.addView(_view, stub.getLayoutParams());

  super.setContentView(baseLayout);
}

有没有办法将 ViewSub 与 View 一起使用而不是替换它?我想inflatedId在我的代码中使用它。或者有人知道我可以用一种完全不同的方法来实现我的目标吗?

4

1 回答 1

0

感谢 Luksprog 的评论,我最终为我的Base活动添加了一个新功能:

protected void addWrappingLayout(int _layoutID, int _stubID) {
  this.wrapViews.add(new LayoutWithStub(_layoutID, _stubID));
}

@Override
public void setContentView(int _layoutID) {
  LayoutInflater               inflater;
  ListIterator<LayoutWithStub> iter;

  ViewGroup                    layout;
  ViewStub                     stub;
  LayoutWithStub               lws;

  if (this.wrapViews.isEmpty()) {
    // There are no wrapping views.
    super.setContentView(_layoutID);
    return;
  }

  iter     = this.wrapViews.listIterator(this.wrapViews.size());
  lws      = iter.previous();

  inflater = this.getLayoutInflater();
  layout   = (ViewGroup) inflater.inflate(lws.getViewResourceID(), null);

  while (iter.hasPrevious()) {
    stub = (ViewStub) layout.findViewById(lws.getStubID());

    lws  = iter.previous();

    stub.setLayoutResource(lws.getViewResourceID());
    stub.inflate();
  }

  stub = (ViewStub) layout.findViewById(lws.getStubID());
  stub.setLayoutResource(_layoutID);
  stub.inflate();

  super.setContentView(layout);
};

子类可以通过注册他们的布局,addWrappingLayout(<their layout resource id>, <the stub id in that layout>)并且Base类会处理这一切。

于 2014-07-14T09:43:40.860 回答