如何设置属于不同活动的按钮的onClickListener
?
我正在使用sharedPreferences
,并且想在其他活动上创建一个注销按钮。启动时打开的活动不应具有注销按钮。这就是为什么我在个人档案活动中没有所有sharedPreferences
代码的原因。
HomeActivity类:
//UserSessionManager class
UserSessionManager session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//start new activity when fab is clicked
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Profile.class);
startActivity(intent);
}
});
session = new UserSessionManager(getApplicationContext());
//check if user is logged in
//if the user is not logged in
if (session.checkLogin()) {
finish();
}
HashMap<String, String> user = session.getUserDetails();
//get variables
String username = user.get(UserSessionManager.KEY_USERNAME);
String age = user.get(UserSessionManager.KEY_AGE);
String firstName = user.get(UserSessionManager.KEY_FIRSTNAME);
EditText etUsername = (EditText) findViewById(R.id.etEmail);
EditText etAge = (EditText) findViewById(R.id.etAge);
我希望注销按钮位于个人资料活动中。
这是配置文件类:
Button bLogOut;
UserSessionManager sessionManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
}
public void sendSession(final UserSessionManager userSession) {
bLogOut = (Button)findViewById(R.id.bLogOut);
bLogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
userSession.logoutUser();
}
});
}
做完许多不同的事情后,我创建了发送会话方法,该方法从
HomeActivity
类接收会话变量作为参数。我仍然有一个nullpointerexception
。 最佳答案
像这样在HomeActivity.class中创建一个接收器,
public BroadcastReceiver logoutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
/Do what ever you want.
}
};
现在在HomeActvity.class中注册和注销您的接收者
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter("com.saim.logoutReceiver");
registerReceiver(logoutReceiver, intentFilter);
}
@Override
protected void onDestroy() {
try {
super.onDestroy();
unregisterReceiver(logoutReceiver);
} catch (IllegalArgumentException i) {
}
}
现在只要通过任何活动发送您的广播
sendBroadcast(new Intent("com.saim.logoutReceiver"));