Android SharedPreference - TabHost问题

时间:2011-09-13 13:21:51

标签: android sharedpreferences android-tabhost

我正在研究Android应用程序,它有两个不同的tabhost:Main和Child。 在主tabhost中我有5个不同的选项卡,最后一个打开我有登录页面的新活动。我想在登录活动中创建一个布尔类型isLoggedIn并将true或false传递给Main Tab栏,因为我想更改数字tab。如果用户已登录,我将有5个,如果不是,我将有4个tabs.So任何建议如何编码此问题?

更新:

现在我正在使用此代码。在用户LogIn.class中,我使用:

SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = isLogged.edit();
        editor.putBoolean("isLoggedIn", isLoggedIn);
        editor.commit();
在MainActivity中,我使用几乎相同的代码:

SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = isLogged.edit();
        editor.putBoolean("isLoggedIn", false);
        editor.commit();

我检查了两个这样的状态:

if(editor.putBoolean("isLoggedIn", false) != null){
// show 5 tabs
}else
{
// show 4 tabs;

但是当我打开我的应用程序时,我会得到5个标签,甚至在检查用户状态之前。 知道怎么解决这个问题吗? }

2 个答案:

答案 0 :(得分:1)

使用

检查共享偏好设置中的值
editor.getBoolean("isLoggedIn", false)

不是使用putBoolean,并且你不必对它放置null,如果共享首选项中不存在名称“isLoggedIn”,它将返回false,这是第二个参数的用途,返回一个如果找不到名称,则为默认值。据我所知,你需要以下代码。

if(editor.getBoolean("isLoggedIn", false)){
// show 5 tabs
}else
{
// show 4 tabs;

此代码将检查“isLoggedIn”值,如果值为true,将显示5个选项卡,如果登录为false,则显示4个。

至于另一个问题,您要在主活动中使用false更新值,不要这样做,只有在用户注销后才这样做。所以从你的代码中删除以下两行。

editor.putBoolean("isLoggedIn", false);
        editor.commit();

答案 1 :(得分:0)

使用sharedPreference,这对整个应用程序来说很常见。