Spinner,ArrayAdapter

时间:2013-07-23 11:31:10

标签: android spinner android-arrayadapter android-spinner

我对Spinner有疑问。我已经设置了ArrayAdapter并设置了OnItemSelected Listener。但是在onClick方法中,它在els-if语句中显示错误。

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

        categorySpinner.setAdapter(adapter);
        categorySpinner.setOnItemSelectedListener(this);

}

private void configureButton2() {
        Button save = (Button) findViewById(R.id.btSave);

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (textName.getText().length() == 0) {
                    textName.requestFocus();
                    return;
                } else if (textContent.getText().length() == 0) {
                    textContent.requestFocus();
                    return;
                } else if (categorySpinner.**getText**().length() == 0) {
                    CategorySpinner.requestFocus();
                    return;
                } else {
                    //next Step: get the mood
                    Intent myIntent = new Intent(v.getContext(), Activity2.class);
                myIntent.putExtra("textName", textName.getText().toString());
                myIntent.putExtra("textContent", textContent.**getText**().toString());
                myIntent.putExtra("CategorySpinner", CategorySpinner.**getText()**.toString());
                v.getContext().startActivity(myIntent);
            }
                }
            }
        });
        }

@Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {

        String selected = parent.getItemAtPosition(pos).toString();

    }

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

    }

我在else-if语句中尝试了这个:

} else if (((CharSequence) docuCategory.getTag()).length() == 0) {
                docuCategory.requestFocus();
                return;

此剂量未显示任何错误,但模拟器“不幸停止”

希望你能帮助我。

1 个答案:

答案 0 :(得分:0)

为什么需要使用getSelectedItemPosition方法来获取所选项目的位置。选定的项目位置将作为参数传递给onItemSelected方法。在您的情况下,变量名称 pos 将是所选项目位置。

试试这个。

@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {

    int selectedPosition = pos;

}

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

}