2014-07-11 57 views
0

我已經得到了活動的層次結構如下:的setContentView(查看_V)和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(),並把給定的佈局到 thier自己的人是這樣的:

/* 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 Activity中做同樣的事情,但是 ,因爲我必須調用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與查看,而不是取代它的方式?我想在我的代碼中使用它的inflatedId。或者有人知道我可以用一種完全不同的方法來實現我的目標嗎?

+1

使用完整視圖將違反小部件的範圍,因此不能,您不能在ViewStub中使用視圖。當你通過這些方法時,你不能僅僅通過傳遞用戶視圖的id來實現所有的東西?然後,在基礎中,您可以獲得第一個ViewStub並膨脹中間的佈局,然後從中間獲取ViewStub並膨脹用戶視圖。 – Luksprog

回答

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>)註冊thier佈局和Base類負責處理這一切。