我的主活动中有一个void返回类型的方法。如果在该方法中创建toast,则会显示错误“类型不匹配:无法将void转换为toast”。有人能解释一下是什么问题并帮我解决吗?

public class HelloList<View> extends ListActivity  {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
 ListView lv=getListView();
      lv.setTextFilterEnabled(true);
      lv.setOnItemClickListener(new OnItemClickListener(){
            @Override

            public void onItemClick(AdapterView<?> arg0,android.view.View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
            //  Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(),Toast.LENGTH_SHORT).show();
                System.out.println(arg2);
                String s="position is "+arg2;
                Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
            }

          });
      registerForContextMenu(lv);
      /*int i=lv.getCheckedItemPosition();
          Toast.makeText(getApplicationContext(),,Toast.LENGTH_SHORT).show();*/
    }
    public void onCreateContextMenu(ContextMenu menu, android.view.View v,
                                    ContextMenuInfo menuInfo) {
      super.onCreateContextMenu(menu, v, menuInfo);
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(0x7f030000, menu);
    }

    public boolean onContextItemSelected(MenuItem item) {
      AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
      switch (item.getItemId()) {
      case 0x7f030000:
        editNote(info.id);
        return true;

      default:
        return super.onContextItemSelected(item);
      }
    }

   public void editNote(long id) {
    Toast m=Toast.makeText(this, "asdasd", 3);
    m.show();

    }

最佳答案

问题是你可以给一个变量分配一个方法。如果要直接显示,吐司应该是这样的:

Toast.makeText(context, text, duration).show();

或者在你的情况下:
Toast.makeText(this, "sadasd", 2).show();

如果要将toast存储在一个变量中,然后将其显示,则必须按如下方式执行:
Toast toast = Toast.makeText(context, text, duration);

toast.show();

或者在你的具体情况下:
Toast toast = Toast.makeText(this, "sadasd", 2);
toast.show();

另一方面:最好在toast中使用常量lenght_short和length_long来定义持续时间,而不是2。尤其是如果2在这里似乎不是有效值。请参见此处了解更多详细信息:http://developer.android.com/reference/android/widget/Toast.html
然后它会像这样:
Toast.makeText(this, "sadasd", Toast.LENGTH_LONG).show();

10-07 12:45
查看更多