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 に答える