2012-02-20 40 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"); 
} 

希望这会有所帮助。

相关问题