有人知道为什么这个程序不会显示toast消息吗?
public class Main extends Activity implements OnClickListener{
/** Called when the activity is first created. */
ImageButton x = (ImageButton) findViewById(R.id.imageButton1);
ImageButton i = (ImageButton) findViewById(R.id.imageButton2);
ImageButton question = (ImageButton) findViewById(R.id.imageButton3);我创建了一些ImageButons和其他元素,并创建了onClick函数
public void onClick(View v) {
if(v.getId() == R.id.button1) // this works
{
Intent intent = new Intent(this, Second.class);
intent.putExtra("thetext", et1.getText().toString());
intent.putExtra("thesize", et2.getText().toString());
startActivity(intent);
}
if(v.getId() == R.id.imageButton2) // this wont work
{
Toast toastI = Toast.makeText(this, "Testing", 5000);
toastI.setGravity(Gravity.CENTER, 0, 0);
toastI.show();
}当我点击ImageButton I(在我运行程序之后),吐司不会显示吗?
发布于 2012-06-24 00:40:02
希望你已经在图像按钮上设置了onclickListener ..
i.setOnClickListener(this);尝尝这个
Toast.makeText(getApplication(), "Testing", 5000).show();发布于 2012-06-24 01:00:19
尝试使用switch case而不是if,并使用Main.this或getApplicationContext()代替this,如下所示:
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent intent = new Intent(Main, Second.class);
intent.putExtra("thetext", et1.getText().toString());
intent.putExtra("thesize", et2.getText().toString());
startActivity(intent);
break;
case R.id.imageButton3:
Toast toastI = Toast.makeText(Main.this, "Testing", 5000);
toastI.setGravity(Gravity.CENTER, 0, 0);
toastI.show();
break;
}
}发布于 2012-06-24 01:28:24
我想你的问题是在吐司的长度上加5000。LENGTH_LONG和LENGTH_SHORT的值分别为1和0,因此它们被用作标志。所以我不知道如果你放5000 (可能什么都不放)会发生什么。另外,在java文档中,他们说你应该放入or或者其他。因此,请使用其中一个。
公共静态吐司makeText (Context context,CharSequence text,int duration)自:API1级创建一个标准的吐司,它只包含一个文本视图。
参数上下文要使用的上下文。通常是您的Application或Activity对象。为要显示的文本添加文本。可以是带格式的文本。持续时间显示消息的时间长度。LENGTH_SHORT或LENGTH_LONG
https://stackoverflow.com/questions/11171162
复制相似问题