Fragment中的微调器的setOnItemSelectedListener()

时间:2016-09-21 16:02:56

标签: java android android-fragments

我试图在我的片段中添加一个微调器和一个监听器。 Android工作室没有向我报告任何错误,但是当我运行它时,它崩溃了这个致命的异常:

14267-14267/? E/AndroidRuntime: FATAL EXCEPTION: main
                                               Process: space.markwen.www.units, PID: 14267
                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{space.markwen.www.units/space.markwen.www.units.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2456)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
                                                   at android.app.ActivityThread.access$900(ActivityThread.java:159)
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:152)
                                                   at android.app.ActivityThread.main(ActivityThread.java:5507)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                   at space.markwen.www.units.LengthActivity.onCreate(LengthActivity.java:40)
                                                   at android.app.Fragment.performCreate(Fragment.java:2198)
                                                   at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:942)
                                                   at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
                                                   at android.app.BackStackRecord.run(BackStackRecord.java:793)
                                                   at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
                                                   at android.app.FragmentController.execPendingActions(FragmentController.java:325)
                                                   at android.app.Activity.performStart(Activity.java:6320)
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2419)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539) 
                                                   at android.app.ActivityThread.access$900(ActivityThread.java:159) 
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384) 
                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                   at android.os.Looper.loop(Looper.java:152) 
                                                   at android.app.ActivityThread.main(ActivityThread.java:5507) 
                                                   at java.lang.reflect.Method.invoke(Native Method) 

片段类:

public class LengthActivity extends Fragment {

    View lengthView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Change FrameLayout to content_length
        lengthView = inflater.inflate(R.layout.content_length, container, false);
        // Change the title on titlebar to Length
        ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Length");
        return lengthView;
    }

    Spinner spinner;
    String[] lengthUnits = {
            "Kilometer", "Meter", "Centimeter", "Millimeter", "Micrometer", "Nanometer", "Mile", "Yard", "Foot", "Inch", "Nautical Mile"};

    @Override
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        spinner = (Spinner) getView().findViewById(R.id.lengthSpinner);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        ArrayAdapter<String> adapter = new ArrayAdapter<String> (getActivity(), android.R.layout.simple_spinner_item, lengthUnits);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }

}

我的观点以防万一你可以找到它的东西:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:weightSum="1">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:ems="10"
        android:id="@+id/editText"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textSize="30dp"
        android:layout_weight="1.01" />

    <Spinner
        android:layout_width="112dp"
        android:layout_height="57dp"
        android:id="@+id/lengthSpinner" />
    <!--android:layout_below="@+id/editText"-->
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp" />
</LinearLayout>

由于

2 个答案:

答案 0 :(得分:2)

将所有onCreate()代码 - 从崩溃的行开始 - 移至onViewCreated()。在调用onCreateView()之前,您无法执行任何此操作,onCreate()之前将调用onCreateView()。在{/ em> onViewCreated()之后,onCreateView()被称为

答案 1 :(得分:0)

根据CommonsWare的建议,工作示例的基本组件如下所示:

enter public class Booking extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_booking, container, false);
return rootView;
}


public void onViewCreated(View rootView, Bundle savedInstanceState){
    super.onViewCreated(rootView, savedInstanceState);
    final View v = rootView;
// Spinner element
Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);

//spinner.setOnItemClickListener(this);

// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("4 Night / 5 Days");
categories.add("5 Night / 6 Days");
categories.add("6 Night / 7 Days");
categories.add("7 Night / 8 Days");

// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories);

// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);


// Spinner click listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view,
                               int position, long id) {

        // On selecting a spinner item
        String item = parent.getItemAtPosition(position).toString();


        // Showing selected spinner item
        Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
});
}
}