2015-09-07 71 views
-4
package com.trid.sharedtask; 

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 

public class MainActivity extends Activity implements OnClickListener { 
    TextView userName, password; 
    Button ok, cancel; 
    SharedPreferences shared; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     userName = (TextView) findViewById(R.id.userName); 
     password = (TextView) findViewById(R.id.password); 
     ok = (Button) findViewById(R.id.ok); 
     cancel = (Button) findViewById(R.id.cancel); 

     userName.setText(shared.getString("key1", "")); 
     password.setText(shared.getString("key1", "")); 

     ok.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View v) { 
     Intent intent = new Intent(getApplicationContext(), Activity2.class); 
     startActivity(intent); 
     SharedPreferences shared = getPreferences(Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor = shared.edit(); 
     editor.putString("key1", userName.getText().toString().trim()); 
     editor.putString("key2", password.getText().toString().trim()); 
     editor.commit(); 

    } 

} 

我必須使用共享首選項創建登錄頁面。如果用戶第一次進入活動,則用戶名和密碼應存儲在共享首選項中。如果用戶輸入連續時間,則共享首選項會將數據提取到用戶名和密碼。使用共享首選項的登錄頁面

感謝您的幫助...!

+5

這是什麼問題? – Breavyn

+0

請查看http://www.gadgetsaint.com/go/xb023 – ASP

回答

0

首先你會檢查共享偏好的值。你會保持默認值爲空白或任何你想要的。如果共享首選項返回空白值,則您將存儲詳細信息,否則您將獲取詳細信息並將與當前值進行比較。

0

在OnClick方法檢查,如果該鍵使用含有(「鍵」)方法就像sharedpreference存在:

@Override 
public void onClick(View v) { 
    Intent intent = new Intent(getApplicationContext(), Activity2.class); 
    startActivity(intent); 
    SharedPreferences shared = getPreferences(Context.MODE_PRIVATE); 
    if(shared.contains("username") && shared.contains("password")){ 

    //Get data from shared preference here and do whatever you want 
    } else { 

    SharedPreferences.Editor editor = shared.edit(); 
    editor.putString("key1", userName.getText().toString().trim()); 
    editor.putString("key2", password.getText().toString().trim()); 
    editor.commit(); 
    } 
}