在Android上使用简单的Spinner时出错

时间:2014-09-04 22:06:32

标签: java android spinner android-spinner

我正在学习Android中的Spinners,并且我已经测试了Android开发者链接中出现的代码: http://developer.android.com/guide/topics/ui/controls/spinner.html

但它不起作用,这些是文件:

MainActivity.java

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

    Spinner spinner = (Spinner) findViewById(R.id.planets_spinner);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
             R.array.planets_array, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinner.setAdapter(adapter);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}
...

fragment_main.xml

<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.spinners.MainActivity$PlaceholderFragment" >

<Spinner
    android:id="@+id/planets_spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

的strings.xml

<?xml version="1.0" encoding="utf-8"?>

<string name="app_name">Spinners</string>    
<string name="action_settings">Settings</string>
<string-array name="planets_array">
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
    <item>Jupiter</item>
    <item>Saturn</item>
    <item>Uranus</item>
    <item>Neptune</item>
</string-array>

当我尝试应用时显示一些错误:

E/AndroidRuntime(1381): FATAL EXCEPTION: main
 Process: com.example.spinners, PID: 1381
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.spinners/com.example.spinners.MainActivity}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
    at android.app.ActivityThread.access$800(ActivityThread.java:135)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
    at com.example.spinners.MainActivity.onCreate(MainActivity.java:28)
    at android.app.Activity.performCreate(Activity.java:5231)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
    ... 11 more

第28行是:

spinner.setAdapter(adapter);

你能解释一下为什么它现在有效吗?谢谢!

2 个答案:

答案 0 :(得分:0)

您当前正在加载布局activity_main.xml:

setContentView(R.layout.activity_main);

但您的微调器在名为fragment_main.xml的布局中定义

变化

setContentView(R.layout.activity_main);

setContentView(R.layout.fragment_main);

编辑: 根据评论,似乎问题是您在尝试从活动中访问其xml布局中的元素之前未加载片段。

答案 1 :(得分:0)

感谢您的回答@maraci,这是解决方案:

填充微调器的代码必须放在片段的类中,在onCreateView方法中,所以MainActivity.java看起来像这样:

public class MainActivity extends ActionBarActivity {

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }                
    }        

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);

            Spinner spinner = (Spinner) rootView.findViewById(R.id.planets_spinner);            
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),R.array.planets_array, android.R.layout.simple_spinner_item);            
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);         
            spinner.setAdapter(adapter);

            return rootView;
        }                
    }
}