从微调器显示吐司时出现上下文错误

Context error when displaying toast from a spinner

我想在用户从微调器中选择一个选项时显示吐司。我一直收到错误,"Cannot resolve method makeText"。我已经尝试使用 getApplicationContext() 并输入 MainActivity.this 但要么仍然存在相同的错误,要么我得到一个额外的错误,指出,

"不兼容的类型。要求:android.widget.Toast"。

public class MainActivity extends AppCompatActivity {

private ImageView equalSign;
private Spinner conversionSpinner, unitOneSpinner, unitTwoSpinner;
private EditText unitOneEditText, unitTwoEditText;
private String[] selectedList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final ArrayAdapter<String> conversionAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, conversion_types);
    conversionSpinner.setAdapter(conversionAdapter);
    conversionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            Toast toastMessage = Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
        }

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

        }
    });
}

使用代码行代替它

Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT).show();

this 在这种情况下指的是 OnItemSelectedListener。所以你需要改变

Toast toastMessage = Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();

Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT).show();

.show 方法没有 return 值。

Incompatible Types. Required: android.widget.Toast

因为将 void 分配给 Toast 对象。

如下所示:Toast.show() 方法 return void 而不是 Toast。这样做:

Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT).show();

或在创建 Toast 对象后调用 show 为:

Toast toastMessage = Toast.makeText(MainActivity.this,"Hello",Toast.LENGTH_SHORT);
toastMessage.show();

您不需要声明 toast 对象。只写

Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();

应该可以。如果可以,请告诉我。