我有一个小登录程序,可将数据保存到共享首选项中。主要活动有"登录"和"帐户" 按钮。当共享首选项为空时,我想禁用登录按钮,并启用"帐户"用户注册我第二个活动帐户的按钮。如果共享首选项为空,如何启用/禁用2个按钮?
活动1
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_interface);
final Button login = (Button)findViewById(R.id.Login);
final Button account = (Button)findViewById(R.id.Account);
login.setEnabled(false);
login.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(MainActivity.this, Summation.class));
}
});
account.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(MainActivity.this, Append.class));
}
});
Button exit = (Button)findViewById(R.id.Exit);
exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
System.exit(0);
}
});
活动2
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Stetho.initializeWithDefaults(this);
setContentView(R.layout.append_interface);
final EditText usernameAppend = (EditText)findViewById(R.id.usernameAppend);
final EditText passwordAppend = (EditText)findViewById(R.id.passwordAppend);
//this buttons appends the username and password to the SharedPreferences
Button append = (Button)findViewById(R.id.Append);
append.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
final SharedPreferences mySharedPref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
final SharedPreferences.Editor editor = mySharedPref.edit();
//Append get data
final String un = usernameAppend.getText().toString();
editor.putString(editorUsername,un);
editor.commit();
final String pw = passwordAppend.getText().toString();
editor.putString(editorPassword, pw);
editor.commit();
if(mySharedPref != null){
Toast.makeText(Append.this,"Account saved",Toast.LENGTH_LONG).show();
startActivity(new Intent(Append.this, MainActivity.class));
}else{
Toast.makeText(Append.this,"Please enter again",Toast.LENGTH_LONG).show();
}
}
}
);
//Exit button,, exits the app
Button exit = (Button)findViewById(R.id.Exit);
exit.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
finish();
System.exit(0);
}
});
}
答案 0 :(得分:0)
在第1次活动中检查您的共享偏好是否存在。第一次它将为null。
btnLogin.setEnabled(false);
btnAccount.setEnabled(false);
SharedPreferences mPrefs=this.getSharedPreferences(Your_Preference_Name,Context.MODE_PRIVATE);
if(mPrefs==null)
{
btnAccount.setEnabled(true);
}
btnAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});