gpt4 book ai didi

java - 底部导航 View 为空

转载 作者:行者123 更新时间:2023-12-01 19:33:50 25 4
gpt4 key购买 nike

我在实现 BottomNavigationView 时遇到运行时异常,

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomnavigation.BottomNavigationView.setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView$OnNavigationItemSelectedListener)' on a null object reference

这是我的代码:

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottom_nav;

@Override
protected void onCreate(Bundle savedInstanceState) {

bottom_nav= findViewById(R.id.bottom_nav);
getSupportFragmentManager().beginTransaction().add(R.id.fragTutucu, new Frag1());

bottom_nav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()){
case R.id.manuel:
fragment= new Frag1();
return true;
case R.id.photo:
fragment= new Frag2();
return true;
case R.id.training:
fragment= new Frag3();
return true;

}
getSupportFragmentManager().beginTransaction().replace(R.id.fragTutucu,fragment);
return true;

}
});


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

最佳答案

您正在尝试在设置 Activity View 之前找到 BottomNavigationView。您应该先设置内容 View 。

按如下方式重新组织代码

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// everything other
}

关于java - 底部导航 View 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58540608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com