如何保存按钮单击Android共享首选项中的事件

时间:2015-12-18 07:18:57

标签: android sharedpreferences android-sharedpreferences

我有两个Activities.Now我想知道如何保存按钮Click-event,就像当我按下按钮想在共享首选项中保存布尔值true时,如果没有按下按钮,则共享中的布尔值为false每次去第二页时都会优先考虑。有人可以帮我解决这个问题。谢谢。这是我的Button Click代码。

  imgBtn_LogOut.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) 
{
 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("strUserName", true);
                    editor.commit();

                    File database = getApplicationContext().getDatabasePath(dbhelper.DATABASE_NAME);

                    if (!database.exists())
                    {
                        Log.e("Database", "Not Found");
                    }
                    else
                    {
                        Log.e("Database", "Found");
                        getApplicationContext().deleteDatabase(dbhelper.DATABASE_NAME);
                        Log.e("Database", " Deleted Completeley !!!");

                        removeImagesFromFolder();

                        Intent i = new Intent(Filter_Screen.this, Login_Screen.class);
                        startActivity(i);
                        finish();
                    }
                }
            });

2 个答案:

答案 0 :(得分:0)

简单地说,你可以这样做,

Filter_Screen:

imgBtn_LogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) 
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("strUserName", true);
editor.commit();
Intent i = new Intent(Filter_Screen.this, Login_Screen.class);
startActivity(i);
finish();
}
});

Login_Screen:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.getBoolean("strUserName",false);
}

答案 1 :(得分:0)

您可以创建

Toast.makeText(this,"button select!",Toast.LENGTH_LONG).show();

对于所有按钮,它可以通知您选择了哪个按钮。 或尝试在if和else语句中使用打印,可能可行。