Toast.LONG 提示著右邊的ImageButton點選後跳出為期3.5秒的Toast
按下Cancel Toast Button後可以關閉Toast(必須透過Handler)
但本範例還不夠完善的是, ImageButton交互點選無法立即清掉Thread裡的sleep()...
package com.tsots.CancelToast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class CancelToast extends Activity
{
Context context = CancelToast.this;
ProgressDialog myDialog = null;
ImageButton ib1;
ImageButton ib2;
Button b3;
String TAG = "CancelToast.this";
Toast toast_start;
Thread thread;
String called_by = null;
volatile boolean terminate = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ib1 = (ImageButton)findViewById(R.id.imagebutton1);
ib2 = (ImageButton)findViewById(R.id.imagebutton2);
b3 = (Button)findViewById(R.id.button3);
ib1.setOnClickListener(new ImageButton.OnClickListener()
{
public void onClick(View arg0)
{
{
called_by = "ib1";
toast_start = Toast.makeText(context, "Start Short Toast", Toast.LENGTH_SHORT);
toast_start.show();
ib1.setBackgroundDrawable(getResources().getDrawable(R.drawable.ib_click));
ib2.setBackgroundDrawable(getResources().getDrawable(R.drawable.ib_unclick));
fun_thread();
}
}
});
ib2.setOnClickListener(new ImageButton.OnClickListener()
{
public void onClick(View arg0)
{
{
called_by = "ib2";
toast_start = Toast.makeText(context, "Start Long Toast", Toast.LENGTH_LONG);
toast_start.show();
ib1.setBackgroundDrawable(getResources().getDrawable(R.drawable.ib_unclick));
ib2.setBackgroundDrawable(getResources().getDrawable(R.drawable.ib_click));
fun_thread();
}
}
});
b3.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View arg0)
{
{
called_by = "b3";
fun_thread();
}
}
});
}
public void fun_thread()
{
new Thread()
{
public void run()
{
try
{
if (called_by.equals("ib1"))
{
sleep(2000);
}
else if(called_by.equals("ib2"))
{
sleep(3500);
}
else
{
Thread.currentThread().interrupt();
handler.sendEmptyMessage(0);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
handler.sendEmptyMessage(0);
}
}
}.start();
}
/*
* 透過Handler將Toast關閉
*/
Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
toast_start.cancel();
ib1.setBackgroundDrawable(getResources().getDrawable(R.drawable.ib_unclick));
ib2.setBackgroundDrawable(getResources().getDrawable(R.drawable.ib_unclick));
}
};
}



沒有留言:
張貼留言