首先要确定引用了这个包:import android.widget.Toast;
其次,在类中药创建私有变量Context:private Context context;
在Activity的onCreate()方法下给context赋值:context=this;//context为当前界面
具体代码是:
Toast.LENGTH_LONG 3.5秒,Toast.LENGTH_SHORT 2秒。
Toast t = Toast.makeText(context,"happy new year", Toast.LENGTH_LONG);
t.show();
代码如下:
package com.example.administrator.dkeyboard;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageButton imageButton;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context=this;
Log.d("i", "onCreate: ");
setContentView(R.layout.activity_main);
imageButton = (ImageButton)findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("123456");
Toast t = Toast.makeText(context,"happy new year", Toast.LENGTH_LONG);
t.show();
}
}
);
}
}
显示效果: