During the project development process, I need to implement the function of "call home", so I used Toast. However, the display time of Toast is not controlled by us. The system only provides two configuration parameters, namely LENGTH_LONG, LENGTH_SHORT. Because to make Toast display for a long time, another thread is needed, and it is displayed cycled every other time period.
Let me first explain that this time, the Handle mechanism needs to be used, so those who don’t understand or are not familiar with Handle, please check out the Handle mechanism on Android first!
Let’s start explaining the details of the code implementation!
Let’s write a packaging class first, and it’s called MyToast, as follows
Copy the codeThe code is as follows:
public class MyToast {
private Context mContext = null;
private Toast mToast = null;
private Handler mHandler = null;
private Runnable mToastThread = new Runnable() {
@Override
public void run() {
();
(mToastThread, 3000);//It is displayed every 3 seconds. After testing, this time interval is the best effect
}
};
public MyToast(Context context){
mContext = context;
mHandler = new Handler(());
mToast = (mContext, "Free@Flying", Toast.LENGTH_LONG);
}
public void setText(String text){
(text);
}
public void show(){
(mToastThread);
}
public void cancel() {
(mToastThread);//Delete the display thread first
();// If you cancel the display effect of the last thread, it will be completely over
}
}
The code for MainActivity is as follows:
Copy the codeThe code is as follows:
public class MainActivity extends Activity implements OnClickListener{
private Button show_button;
private Button cancel_button;
private MyToast myToast;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView();
show_button = (Button) findViewById(.show_button);
cancel_button = (Button) findViewById(.cancel_button);
show_button.setOnClickListener(this);
cancel_button.setOnClickListener(this);
myToast = new MyToast(this);
}
@Override
public void onClick(View v) {
if(v == show_button){
();
}else if (v == cancel_button) {
();
}
}
}