底部导航视图片段NullPointerException
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了底部导航视图片段NullPointerException相关的知识,希望对你有一定的参考价值。
在我的一个片段中,我在xml中有一个切换按钮:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.stefan.findage.piano">
<!-- TODO: Update blank fragment layout -->
<ToggleButton
android:id="@+id/metronome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
</FrameLayout>
和
toggleButton = (ToggleButton) getView().findViewById(R.id.metronome);
但是当试图打开片段时它会崩溃并且logcat显示它是一个
java.lang.NullPointerException:尝试在空对象引用上调用虚方法'android.view.View android.view.View.findViewById(int)'
这是主要活动:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottomView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.moosic:
rhythm fragmentone = new rhythm();
android.support.v4.app.FragmentTransaction fragmentTransaction3 = getSupportFragmentManager().beginTransaction();
fragmentTransaction3.replace(R.id.frame, fragmentone, "rhythm");
fragmentTransaction3.commit();
return true;
case R.id.call:
intervals fragmenttwo = new intervals();
android.support.v4.app.FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction();
fragmentTransaction2.replace(R.id.frame, fragmenttwo, "intervals");
fragmentTransaction2.commit();
return true;
case R.id.thinga:
piano fragmentthree = new piano();
android.support.v4.app.FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.frame, fragmentthree, "piano");
fragmentTransaction1.commit();
return true;
}
return false;
}
});
}
}
答案
getView()可能返回null。使用以下代码引用切换按钮
View view = inflater.inflate(R.layout.fragmentlayout, container, false);
toggleButton = (ToggleButton) view.findViewById(R.id.metronome);
以上是关于底部导航视图片段NullPointerException的主要内容,如果未能解决你的问题,请参考以下文章