2

我的应用程序有一个登录屏幕。(微调器,edittext,按钮),我想将微调器选定的项目和输入的文本存储到共享首选项。在应用程序的任何地方使用。

代码

Button lgnbutton;
EditText lgnfield;
Spinner lgnspinner;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

lgnbutton = (Button) findViewById(R.id.loginbutton);
lgnfield = (EditText) findViewById(R.id.loginfield);
lgnspinner = (Spinner) findViewById(R.id.loginspinner);





lgnbutton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub

        String ID = lgnfield.getText().toString();
        String Type = lgnspinner.getSelectedItem().toString();


        Intent myIntent = new Intent(LoginActivity.this, MainActivity.class);
        LoginActivity.this.startActivity(myIntent);
    }
});
}    
}

跳过登录活动并继续进行主要活动也会很好。

4

2 回答 2

2

在微调器单击时调用它

   SavePreferences("spinner_item",  mySpinner.getSelectedItem().toString());

SavePreferences 方法的主体。

     private void SavePreferences(String key, String value){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
       }

调用此方法以加载微调器项目。

private void LoadPreferences(){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    String strSavedMem = sharedPreferences.getString("spinner_item", "");
     }
于 2012-12-22T11:09:19.943 回答
1

您可以在 SharedPreferences 中存储登录详细信息和微调器选定项目

lgnbutton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub

         ID = lgnfield.getText().toString();
         Type = lgnspinner.getSelectedItem().toString();

        SharedPreferences.Editor prefsEditor = loginpreferences.edit();
        prefsEditor.putString("ID", ID);
        prefsEditor.putString("Type", Type);
        prefsEditor.commit();

        Intent myIntent = new Intent(LoginActivity.this, MainActivity.class);
        LoginActivity.this.startActivity(myIntent);
    }
});

并检查是否存在登录详细信息,onCreate如果是,则移至:LoginActivitySharedPreferencesMainActivity

SharedPreferences loginpreferences;
String ID="",Type="";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    loginpreferences = this.getSharedPreferences("loginPrefs", 
                                            MODE_WORLD_READABLE);

    ID = loginpreferences.getString("ID", "");
    Type = loginpreferences.getString("Type", "");

     if(!ID.equalsIgnoreCase("") && !Type.equalsIgnoreCase(""))
      {
        //move to MainActivity
      }else
     {
       //stay in LoginActivity
     }
于 2012-12-22T11:09:42.253 回答