今天要來介紹一下android的全域變數
原本,我用android做會員登入時,都是用bundle下去傳值
但是,當頁面一多,就感覺很麻煩.....
改用全域變數吧,這樣就會輕鬆很多囉~~
以下開始:
-----------------------------------
首先,先建一個java檔,叫做GlobalVariable
把你要的變數寫進去,我需要存帳號跟密碼
import android.app.Application;
public class GlobalVariable extends Application {
private String Account; //User 帳號
private String Passwd; //User 密碼
public String getAccount() {
return Account;
}
public void setAccount(String account) {
this.Account = account;
}
public String getPasswd() {
return Passwd;
}
public void setPasswd(String passwd) {
this.Passwd = passwd;
}
}
接著,在androidmainfest.xml中的application加入
<application android:name=".GlobalVariable"
在你要登入的頁面中加入這些程式碼
GlobalVariable Account = (GlobalVariable)getApplicationContext();
Account.setAccount(account);
Account.setPasswd(passwd);
登入頁面的完整程式
public class Login extends AppCompatActivity {
private TextView acc,pwd;
private Button btn;
String mycart="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
acc=(TextView)findViewById(R.id.acc);
pwd=(TextView)findViewById(R.id.pwd);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(btnlogin);
}
private Button.OnClickListener btnlogin=new Button.OnClickListener(){
public void onClick(View v){
String account=acc.getText().toString();
String passwd=pwd.getText().toString();
GlobalVariable Account = (GlobalVariable)getApplicationContext();
Account.setAccount(account);
Account.setPasswd(passwd);
if(account=="123" &&passwd=="123")
{
Intent intent= new Intent();
intent.setClass(Login.this, Mcart.class);
startActivity(intent);
}
}
};
}
以上,你已經把帳密都存到globalvirable裡面了
接下來,就是如何取出來了
登入後會跳到第二頁面,所以第二頁面的程式是
GlobalVariable Account = (GlobalVariable)getApplicationContext(); account=Account.getAccount(); passwd=Account.getPasswd();
這樣就可以將值取出來使用了
完畢!!
留言列表