我正在尝试制作一个微调器,我在Internet上找到了很多教程。 但它总是会导致错误。 (空对象引用)
Q1:为什么我写
setContentView(R.layout.activity_main); before
Spinner dynamicSpinner =(Spinner) findViewById(R.id.spinnerFindType);`它仍会导致空错误?Q2:我的微调器在另一个xml(find_fragment)中,所以我应该改变 从
中setContentView(R.layout.activity_main);
到。{setContentView(R.layout.find_fragment);
? 但这是在MainActivity.java
非常感谢你!
这是我的代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ---------------------------- Init Menu slider -----------------------------------
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null); // show Icon
navigationView.setNavigationItemSelectedListener(this);
displayView(R.id.menu_about); // First page to About
// ---------------------------------------------------------------------------------
Spinner dynamicSpinner = (Spinner) findViewById(R.id.spinnerFindType);
String[] items = new String[] { "A", "B", "C" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items); // Use String[] , Dynamic
dynamicSpinner.setAdapter(adapter);
dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), (String) parent.getItemAtPosition(position), Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
我的logcat:
引起:java.lang.NullPointerException:尝试调用虚拟 方法&#39;无效 android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)&#39;在...上 null对象引用 在com.example.user.foody.MainActivity.onCreate(MainActivity.java:120) 在android.app.Activity.performCreate(Activity.java:6288) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)