这是我主要活动中的退出按钮,效果很好。顺便说一句,我使用的是Firebase,这是Google登录的退出按钮。它在我的主要班级时按预期工作。
package com.example.akhilsukh01.truckory;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth;
public class HomeActivity extends AppCompatActivity {
Button button;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
button = (Button) findViewById(R.id.logout);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(HomeActivity.this, MainActivity.class));
}
}
};
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAuth.signOut();
}
});
}
}
我知道它不会使用相同的代码,因为它不是一项活动而且它完全是一个不同的片段,但我不确定如何修复它。这是我的尝试(不起作用):
package com.example.akhilsukh01.truckory;
/**
* Created by akhil on 7/24/2017.
*/
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth;
public class Tab5Profile extends Fragment {
Button button;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.tab5profile, container, false);
return rootView;
Button logout = (Button) rootView.findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Logout current user
mAuth.signOut();
startActivity(new Intent(HomeActivity.this, LoginActivity.class));
}
});
}
}
答案 0 :(得分:0)
如果它在活动中工作正常,则不要更改代码。在片段使用中
((HomeActivity)getActivity).mAuth.signOut();