按下按钮时,从微调器向CommitPreferences提交值

时间:2013-10-14 01:31:03

标签: android spinner sharedpreferences

我正在尝试让用户从微调器中选择一个项目,当按下“提交”按钮时,将数据提交给SharedPrefences。

这是微调器所在的位置:

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

    Spinner spinner = (Spinner) findViewById(R.id.dob_month);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.months_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);

}

以下是按下提交按钮时方法中的内容:

String Text = spinner.getSelectedItem().toString();
    editor.putString("dob_month",dobMonth).commit();

1)在按下按钮的方法中,'spinner'未定义

2)我知道我错过了旋转器的监听器,我将如何以及在何处实现?

3 个答案:

答案 0 :(得分:0)

您是否声明并初始化了共享首选项和编辑器对象?

答案 1 :(得分:0)

您已在onCreate()初始化了微调器,因此该方法之外的任何人都无法访问它。

将其更改为此

    Spinner mSpinner;

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

    mSpinner = (Spinner) findViewById(R.id.dob_month);
    ...

答案 2 :(得分:0)

以下是使微调器工作所需的一切:

protected void onCreate(Bundle savedInstanceState) {



    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_youractivity);
    Spinner spinner=(Spinner)findViewById(R.id.spinnerxmlname);
    spinner.setOnItemSelectedListener(this);
    List<String> items=new ArrayList<String>();
            items.add()= //set all month names
            ArrayAdapter<String> adapter =new  ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item,items );
    // 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);

            }


@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
        long id) {
    // TO code what should be done when an item is selected,in your case commit
            //to sharedpreferences
    String Text = spinner.getSelectedItem().toString();
            editor.putString("dob_month",
                                        (String)parent.getItemAtPosition(pos).commit();

    }
@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}

另请注意,您的Activity应实现OnItemSelectedListener接口