[英]Android - Where should I place my listeners?
我在嘗試確定將聽眾放置在哪里時遇到了問題(我正在嘗試設置兩個聽眾,但這里只引用其中一個,希望可以自己為第二個聽眾做准備!)。
我有一個微調器,並且想在微調器項更改時更新一些TextViews,因此認為我需要一個onItemSelected
偵聽器。 在閱讀了SO上其他人的問題后,我嘗試將其放在onCreate
方法和onStart
方法中,但是應用程序在加載時將只是FC。
該應用程序使用“選項卡/片段”進行導航,這可能與問題有關(嘗試設置偵聽器時片段未膨脹)?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
spinner = (Spinner)findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
還有logcat;
08-24 17:19:16.256 13803-13803/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
... 11 more
當您在spinner.setXXX()
獲得NullPointerException時,您的spinner
變量將包含null。 這意味着之前的pine中的findViewById()
在當前上下文中未找到微調器。 使用您的setContentView()
行設置上下文。
底線:看起來您的R.layout.activity_main
不包含R.id.spinner
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.