2011-09-05 57 views
4

我目前使用的是SearchView對象,以便爲我的應用程序功能提供建議的輸入。從SearchView更改片段提交aka級聯向下疊加

然而,這個小部件在提交時使用intent-filter來啓動您的搜索。當我的應用程序在手機上運行時,這非常棒,因爲我想要啓動搜索結果Activity以顯示響應。 不過在平板電腦上我想要它加載我的搜索結果在當前Activity的片段!

我希望我的應用程序儘可能統一(就電話/標籤之間的交叉而言),而不是像建議的那樣覆蓋提交行爲in this answer我希望開始一個新的活動,將搜索項路由到它需要去。在通往結果活動的電話中,我希望將searchTerm傳遞給前一個活動。

所以我想問一下 - 你能否把信息傳遞給後面的Activity?

回答

4

我建議你有你的SearchCatchingActivity充當路由活動。它可以捕獲查詢並將其傳遞給所需的活動(無論是結果片段的雙窗格還是具有單個結果片段的單個窗格)。在路由到下一個Activity時使用FLAG_ACTIVITY_CLEAR_TOP intent標誌,以便它成爲該實例的默認Activity。請記住在路由活動上調用finish()以將其從堆棧中移除。

+0

使用FLAG_ACTIVITY_CLEAR_TOP有效地去除這是在返回堆棧和較低活性的實例重新實例化它ontop的。當用在直接上一個Activity上時,你實際上在後臺調用了「Back」。 – Graeme

0

我當前的解決方案(很髒)是在同一活動中有一個公共靜態字符串,它在Activity恢復時進行檢查,如果發現使用該字詞開始搜索並清除靜態變量。

public class SearchCatchingActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState); 

    // Ensure this activity isn't in the backstack, notify the previous activity in the backstack that it should handle the search onResume() 
    DualPaneActivity.searchTerm = getIntent().getStringExtra(SearchManager.QUERY); 
    finish(); 

} 

DualPaneActivity:

if (!searchTerm.equalsIgnoreCase("")) { 
    startSearchThread(searchTerm) 
    searchTerm = ""; 
} 
1

我只是將我的活動的啓動模式設置爲singleTop,併爲此處理onNewIntent方法。

AndroidManifest.xml中

<activity android:name=".MyActivity" android:launchMode="singleTop" android:theme="@style/Theme.MyTheme" > 
    <intent-filter > 
     <action android:name="android.intent.action.SEARCH" /> 
    </intent-filter> 

    <meta-data 
     android:name="android.app.searchable" 
     android:resource="@xml/searchable" /> 
</activity> 

MyActivity.java (這顯然是過於簡單化了 - 你可能只是對你的現有片段的公共方法傳遞它的搜索查詢在下面的例子中我更換。它與一個全新的片段。)

@Override 
protected void onNewIntent (Intent intent) { 

    MyFragment newFrag = new MyFragment(); 
    newFrag.setArguments(args); 

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 

    // remove previous show list fragment if it exists 
    Fragment prev = getSupportFragmentManager().findFragmentByTag("myFrag"); 
    if (prev != null) { 
     ft.remove(prev); 
    } 
    ft.add(R.id.fragment_placeholder, newFrag, "myFrag"); 
    ft.commit(); 

}