我在我的主要活动中有一个方法是void返回类型.如果我在方法中创建一个Toast,它会显示错误“类型不匹配:无法将void转换为toast”.任何人都可以解释什么是问题,并帮助我解决方案? p
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();