2012-02-20 43 views
0

Android開發的第一天,請原諒任何無知。從另一個選項卡上的字段讀取值

我的MainActivity類別具有下面的代碼:

// Create the tabs 
    intent = new Intent().setClass(this, DisplayActivity.class); 
    spec = tabHost.newTabSpec("Display") 
       .setIndicator("Display") 
       .setContent(intent); 
    tabHost.addTab(spec); 

    intent = new Intent().setClass(this, SettingsActivity.class); 
    spec = tabHost.newTabSpec("Settings") 
       .setIndicator("Settings") 
       .setContent(intent); 
    tabHost.addTab(spec); 

我想要檢索的字段在顯示選項卡中設置的值。我怎樣才能做到這一點?

回答

1

爲什麼不使用「共享偏好」?當字段設置時,更新首選項。當您需要顯示時,請閱讀首選項。有關詳情,請參閱Data Storage

1

有2-3種方法可以做到這一點 1.在應用程序級別使用變量 2.使用共享首選項。

創建使用getter setter方法擴展Application的類。在一個活動

Times myApp = ((Times)getApplication()); // where Times is my getter setter class 
                 which extends Applicaton 
myApp.setHour1(5); 

設置數據在另一個活動

Times myApp = ((Times)getApplication()); 
int variable = (myApp.getHour1()); 

不要忘記在清單文件提烏爾應用級的類名稱,如獲取數據:

<application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:name=".Times" 
    > 

最佳幸運

0

我使用稍微不同的方法,然後是其他人在帖子中建議的方法。

我把通用數據對象在不同標籤中的活動共享到添加標籤時傳遞的意圖中。在你的榜樣,使用這種方法的代碼將如下所示:

// Create the tabs 
MyObject myObj = new MyObj(); 
//MyObject should implement android.os.Parcelable interface 
intent = new Intent().setClass(this, DisplayActivity.class); 
intent.putExtra("myObjKey", myObj); 
spec = tabHost.newTabSpec("Display") 
      .setIndicator("Display") 
      .setContent(intent); 
tabHost.addTab(spec); 

intent = new Intent().setClass(this, SettingsActivity.class); 
intent.putExtra("myObjKey", myObj); 
spec = tabHost.newTabSpec("Settings") 
      .setIndicator("Settings") 
      .setContent(intent); 
tabHost.addTab(spec); 

在個人活動相同的對象可以從提供給活動時,它推出的意圖來獲得。

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.somecontentlayout); 
    MyObject myObj = getIntent().getParcelableExtra("myObjKey"); 
} 

希望這會有所幫助。

相關問題