我从空活动创建 drawer
,所以我不使用fragment
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
private Button signOut;
private DrawerLayout nDrawer;
private ActionBarDrawerToggle nToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
当我把这个setNavigaionViewListener
,这个活动会在构建时崩溃,我在某个地方出错了吗?
//setNavigationViewListner();
//get firebase auth instance
auth = FirebaseAuth.getInstance();
并且我不知道为什么但是让当前用户无法工作但我没有得到错误的位置。
//get current user
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
authListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
signOut = (Button) findViewById(R.id.sign_out);
nDrawer = (DrawerLayout) findViewById(R.id.drawer);
nToggle = new ActionBarDrawerToggle(MainActivity.this,nDrawer,R.string.open,R.string.close);
nDrawer.addDrawerListener(nToggle);
nToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
signOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (nToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
//method to set Listener
private void setNavigationViewListner() {
NavigationView navigationView = (NavigationView) findViewById(R.id.drawer);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.account:{
startActivity(new Intent(MainActivity.this, ProfileActivity.class));
break;
}
case R.id.logout:{
signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
break;
}
}
nDrawer.closeDrawer(GravityCompat.START);
return true;
}
//sign out method
public void signOut() {
auth.signOut();
}
答案 0 :(得分:0)
使用此
Toolbar toolbar = (Toolbar) findViewById(R.id.Yourtoolbar);
nToggle = new ActionBarDrawerToggle(
MainActivity.this, nDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
而不是
nToggle = new ActionBarDrawerToggle(MainActivity.this,nDrawer,R.string.open,R.string.close);
并更改此删除
DrawerLayout
findViewById(R.id.drawer)
并将您的NavigationView
ID
示例
findViewById(R.id.YournavigationView);
NavigationView navigationView = (NavigationView) findViewById(R.id.YournavigationView);