2013-05-05 131 views
0

我想加載一個佈局XML文件並將佈局廣告到當前的內容視圖。如何加載佈局並將其添加到Android中的其他佈局?

所以,如果我得到這個佈局在這裏:

Layout without search bar.

,如果我打了硬件搜索按鈕,然後我要顯示在屏幕頂部的搜索欄,如下所示:

Layout with search bar.

基於this answer,我想是這樣的:

MainActivity.java

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View v = inflater.inflate(R.layout.search_bar, null); 

    ViewGroup layout = (ViewGroup) findViewById(R.id.layout_main); 
    layout.addView(v); 
} 

搜索欄名爲search_bar.xml佈局文件。主要活動是R.layout.activity_mainR.id.layout_mainRelativeLayout的編號,它是activity_main中的容器。

但我得到了錯誤膨脹類

如何加載佈局並將其添加到當前加載的佈局?

+0

什麼錯誤?你能給我們提供LogCat嗎? – Ahmad 2013-05-05 19:12:26

回答

1

我沒有看到你的代碼有一個明顯的問題。正如在評論中提到的,請在這裏發佈日誌。

我可以提出另一種方法嗎?您可以包含搜索欄(在主佈局中或使用include標籤),並將其可見性設置爲GONE,直到您需要顯示它。

0

我做了一些研究,並將幾個提示結合起來。
首先,我用LayoutInflater.from(Context)而不是Context.LAYOUT_INFLATER_SERVICE(雖然這似乎不是問題)。其次,我使用了onSearchRequest()方法。

這是結果:

/** 
* Whether the search bar is visible or not. 
*/ 
private boolean searchState = false; 

/** 
* The View loaded from the search_bar.xml layout. 
*/ 
private View searchView; 

/** 
* This method is overridden from the Activity class, enabling you to define events when the hardware search button is pressed. 
* 
* @return Returns true if search launched, and false if activity blocks it. 
*/ 
public boolean onSearchRequested() { 
    // Toggle the search state. 
    this.searchState = !this.searchState; 
    // Find the main layout 
    ViewGroup viewGroup = (ViewGroup) findViewById(R.id.layout_main); 
    // If the search button is pressed and the state has been toggled on: 
    if (this.searchState) { 
     LayoutInflater factory = LayoutInflater.from(this.activity); 
     // Load the search_bar.xml layout file and save it to a class attribute for later use. 
     this.searchView = factory.inflate(R.layout.search_bar, null); 
     // Add the search_bar to the main layout (on position 0, so it will be at the top of the screen if the viewGroup is a vertically oriented LinearLayout). 
     viewGroup.addView(this.searchView, 0); 
    } 
    // Else, if the search state is false, we assume that it was on and the search_bar was loaded. Now we remove the search_bar from the main view. 
    else { 
     viewGroup.removeView(this.searchView); 
    } 
    return false; 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
}