全栈工程师开发手册 (作者:栾鹏)
​​ 安卓教程全解​​

安卓Toast显示提示消息。

使用系统自带Toast提示框

//显示一个Toast
private void displayToast() {
Context context = this;
String msg = "要显示的消息"; //要显示的消息
int duration = Toast.LENGTH_SHORT;//显示时长
Toast toast = Toast.makeText(context, msg, duration); //创建弹出窗口

//自定义toast位置
int offsetX = 0;
int offsetY = 0;
toast.setGravity(Gravity.BOTTOM, offsetX, offsetY); //设定显示位置

toast.show(); //显示提示框
}

使用view来自定义一个Toast

private void displayCustomViewToast() {
Context context = getApplicationContext();
String msg = "要显示的消息";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, msg, duration);
toast.setGravity(Gravity.BOTTOM, 0, 0);

//自定义一个view,你也可以直接将xml转化为view对象

LinearLayout ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.VERTICAL);

TextView myTextView = new TextView(context);
myTextView.setText(msg);
myTextView.setTextColor(Color.RED);

int lHeight = LinearLayout.LayoutParams.FILL_PARENT;
int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
ll.addView(myTextView, new LinearLayout.LayoutParams(lHeight, lWidth));
ll.setPadding(40, 50, 0, 50);
//为toast设置view
toast.setView(ll);
toast.show();
}

Toast实时提醒子线程传来的消息

由于toast只能在主线程中打开,所以如果你的函数在子线程中运行,需要向主线程发送信号,主线程接收信号后,才能打开toast

包含三个步骤,1、开启子线程,2、在主线程中定义消息处理对象,负责接收子线程传来的消息,进更新UI,3、子线程中向主线程定义的消息处理对象发送消息。

实现方法有两种:

第一种方法:

//启动子线程
private void open_subthread() {
Thread thread = new Thread(null, doBackgroundThreadProcessing,"Background");
thread.start();
}

//定义子线程
private Runnable doBackgroundThreadProcessing = new Runnable() {
public void run() {
//这里是你要进行的计算
//....
//向主线程发送信息
handler.sendEmptyMessage(0);
}
};

//定义一个消息机制,接收子线程信息
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
Context context = getApplicationContext();
String msgtext = "显示消息";
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, msgtext, duration).show();
break;
}
}
};

第二种方法:

//启动子线程
private void open_subthread() {
Thread thread = new Thread(null, doBackgroundThreadProcessing,"Background");
thread.start();
}

Handler handler = new Handler();
//定义子线程
private Runnable doBackgroundThreadProcessing = new Runnable() {
public void run() {
//这里是你要进行的计算
//....
//向主线程发送信息
handler.post(doUpdateGUI); //子线程向GUI主线程发送更新消息
}
};

//执行更新GUI方法的Runnable
private Runnable doUpdateGUI = new Runnable() {
public void run() {
Context context = getApplicationContext();
String msg = "显示消息";
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, msg, duration).show();
}
};