在Fragment中加载微调器时出错

时间:2014-01-09 11:03:38

标签: android android-fragments android-spinner

我有使用类扩展Activity加载微调器的代码。这是成功的工作。这是代码......

package nielpoenya.blogspot.com;

import....

public class MySQLite extends Activity implements OnItemSelectedListener {
    Spinner spinner;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        spinner = (Spinner) findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(this);

        loadSpinnerData();

    }

    /**
     * Function to load the spinner data from SQLite database
     * */
    private void loadSpinnerData() {
        // database handler
        DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 

        // Spinner Drop down elements
        List<String> lables = db.getAllLabels();

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

        // 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);
    }

    @Override
    public void onItemSelected.....

现在我想在课堂上尝试使用extends Fragment,但它会让它停止工作..

package com.tugasbesar.medantrain;

import....

public class InfoJadwal extends Fragment implements OnItemSelectedListener {

    Spinner spinner;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.info_jadwal, container, false);

        spinner = (Spinner) getActivity().findViewById(R.id.spin_tujuan);
        spinner.setOnItemSelectedListener(this);

        loadSpinnerData();

        return rootView;
    }

    private void loadSpinnerData() {
        // database handler
        DatabaseHandler db = new DatabaseHandler(this.getActivity());

        // Spinner Drop down elements
        List<String> lables = db.getAllLabels();

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

        // 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);
    }

    @Override
    public void onItemSelected....

我的片段类缺少什么?感谢

1 个答案:

答案 0 :(得分:2)

错误在onCreateView,您需要替换:

spinner = (Spinner) getActivity().findViewById(R.id.spin_tujuan);

by:

spinner = (Spinner) rootView.findViewById(R.id.spin_tujuan);

因为使用getActivity().findViewById(),它会尝试在Activity的内容视图中搜索视图,而不是Fragment