在我的一个片段中,我在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:尝试调用虚方法&#39; android.view.View android.view.View.findViewById(int)&#39;在空对象引用上
这是主要活动:
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;
}
});
}
}
答案 0 :(得分:0)
getView()可能返回null。使用以下代码引用切换按钮
View view = inflater.inflate(R.layout.fragmentlayout, container, false);
toggleButton = (ToggleButton) view.findViewById(R.id.metronome);