2015-04-23 60 views
0

我想在兩個TabHost活動之間傳遞數據但未成功。 這裏是我的代碼:如何傳遞數據在TabHost的活動android

public class AndroidTabLayoutActivity extends TabActivity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     TabHost tabHost = getTabHost(); 

     TabSpec livedata = tabHost.newTabSpec("Photoes"); 
     livedata.setIndicator("Photoes", getResources().getDrawable(R.drawable.icon_photos_tab)); 
     Intent livedataIntent = new Intent(this, PhotosActivity.class); 
     livedata.setContent(livedataIntent); 

     TabSpec addedlegs = tabHost.newTabSpec("Songs"); 
     addedlegs.setIndicator("Songs", getResources().getDrawable(R.drawable.icon_songs_tab)); 
     Intent addedlegsIntent = new Intent(this, SongsActivity.class); 
     addedlegs.setContent(addedlegsIntent); 

     tabHost.addTab(livedata); 
     tabHost.addTab(addedlegs);   
    } 
} 

main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/tabhost" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"> 
     <TabWidget 
      android:id="@android:id/tabs" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" /> 
     <FrameLayout 
      android:id="@android:id/tabcontent" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent"/> 
    </LinearLayout> 
</TabHost> 

輸出圖像: enter image description here 我在表演PhotosActivity.class(這是在第一個選項卡(Photoes))計算的一些活動,我想將結果作爲字符串傳遞給SongsActivity.class(在第二個選項卡(歌曲)中),我使用此字符串進行進一步計算。

任何人都可以提出一種方法來實現嗎? Thanx inadvance !!

回答

0

家長activity與其孩子之間溝通的想法是使用相關聯的tags,在您的情況下是「Photoes」和「Songs」。

例如:如果您需要將Tab「Photoes」中的字符串傳遞給父活動。

1),你需要在父activity創建一個公共方法,然後調用它從孩子以下

((AndroidTabLayoutActivity)getParent()).myFunctionName("string value"); 

2)此值傳遞給特定的子,e.g。 「歌曲」,那麼你必須在這個孩子activity內創建一個公共方法,並使用它的Tag從父母中調用它。

public void myFunctionName(String str){ 
    ActivityTab1 activity = (ActivityTab1) getLocalActivityManager().getActivity("Tab1"); 
    activity.takeThisValue(str); 
} 

你也可能需要做一些驗證,以確保活動的情況下,不null

if(activity !=null) 
//DO my stuff 

參考:https://androidactivity.wordpress.com/2012/08/17/two-way-communication-between-tabactivity-and-its-child-tabs/

相關問題