我是Android编程的新手,我正在尝试实现微调器,但setOnItemSelectedListener,setDropDownViewResource和setAdapter出现“无法解析符号”错误。我很困惑我尝试添加更多的导入,但是它们什么也没做。

这是我的代码:

public class MainActivity extends AppCompatActivity implements OnItemSelectedListener {
    public final static String EXTRA_MESSAGE = "com.example.FinalProject.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

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

// Create an ArrayAdapter using the string array and a default spinner layout

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.verb_endings_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);

    public void onItemSelected(AdapterView<?> parent, View view,
                           int pos, long id) {
        // An item was selected. You can retrieve the selected item using
        // parent.getItemAtPosition(pos)
    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

最佳答案

移动这个

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


在onCreate方法中,但在外部声明微调器,(您肯定以后要使用它... :))

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

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

10-06 06:46