2011-06-16 160 views
4

我試圖創建一個活動來搜索,並有2個不同的佈局與每個不同的搜索條件。我想用一個微調來做到這一點。真的沒有任何代碼,因爲我已經嘗試過,我刪除了,但任何幫助表示讚賞。動態更改佈局

+1

我不跟着你真正想要做什麼? – dymmeh 2011-06-16 15:52:24

+0

是的,我寫這篇文章時可能已經失去了我的思路,但我使用的Web服務搜索有兩種不同類型的搜索,這兩種搜索都有不同的搜索條件。我想要2種不同的佈局,每種搜索1種。我想要一個下拉菜單能夠在2. – digipen79 2011-06-16 16:13:00

回答

7

您可以使用Activity.setContentView()將活動的整個內容視圖切換到onItemSelected回調中的新視圖或佈局資源,但我認爲這並不完全符合您的想法,因爲它將替代微調器本身。

如何在您的活動內容視圖中添加/替換子視圖?這可能是一個來自XML資源的膨脹視圖,他們可以共享一些視圖ID以減少所需的代碼(或者可以將行爲委託給不同的類)。

例如:

main.xml

<LinearLayout ...> <!-- Root element --> 
    <!-- Put your spinner etc here --> 
    <FrameLayout android:layout_height="fill_parent" 
       android:layout_width="fill_parent" 
       android:id="@+id/search_criteria_area" /> 
</LinearLayout> 

search1.xml

<!-- Contents for first criteria --> 
<LinearLayout ...> 
    <TextView android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:background="#ffff0000" 
       android:id="@+id/search_content_text" /> 
</LinearLayout> 

search2.xml

<!-- Contents for second criteria --> 
<LinearLayout ...> 
    <TextView android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:background="#ff00ff00" 
       android:id="@+id/search_content_text" /> 
</LinearLayout> 

然後,在你的活動,你可以象這樣在它們之間進行切換:

public class SearchActivity extends Activity { 

    // Keep track of the child view with the search criteria. 
    View searchView; 

    @Override 
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 

     ViewGroup searchViewHolder = (ViewGroup)findViewById(R.id.search_criteria_area); 

     if (searchView != null) { 
      searchViewHolder.removeView(searchView); 
     } 

     int searchViewResId; 

     switch(position) { 
     case 0: 
      searchViewResId = R.layout.search1; 
      break; 
     case 1: 
      searchViewResId = R.layout.search2; 
      break; 
     default: 
      // Do something sensible 
     } 

     searchView = getLayoutInflater().inflate(searchViewResId, null); 
     searchViewHolder.addView(searchView); 

     TextView searchTextView = (TextView)searchView.findViewById(R.id.search_content_text); 
     searchTextView.setText("Boosh!"); 
    } 
} 
+0

之間切換,非常感謝,這將非常好地工作 – digipen79 2011-06-16 17:32:10