setContentView(View _v)和ViewStub

时间:2014-07-11 13:40:36

标签: android user-interface viewstub

我有以下活动层次结构:

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。或者有人意识到我可以用来实现目标的完全不同的方法吗?

1 个答案:

答案 0 :(得分: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类可以处理所有这些。