Android开发之《实现类似Toast可以自动消失的提示栏Tip》

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android开发之《实现类似Toast可以自动消失的提示栏Tip》相关的知识,希望对你有一定的参考价值。

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.TextView;

public class TipManager {
    private static final String TAG = TipManager.class.getSimpleName();

    private Context mContext;
    private TextView mView;

    private Timer timer = null;
    private TimerTask cancelTask = null;

    public TipManager(Context context, TextView view) {
        mContext = context;
        mView = view;
    }

    public void init() {
        timer = new Timer();
    }

    public void release() {
        if (cancelTask != null) {
            cancelTask.cancel();
            cancelTask = null;
        }

        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void show(CharSequence text) {
        // cancel hide task
        if (cancelTask != null) {
            cancelTask.cancel();
            cancelTask = null;
            timer.purge();
        }

        showUI(text);
    }

    public void show(CharSequence text, long duration) {
        showUI(text);

        // cancel hide task
        if (cancelTask != null) {
            cancelTask.cancel();
            cancelTask = null;
            timer.purge();
        }

        cancelTask = new TimerTask() {
            @Override
            public void run() {
                hideUI("default");
            }
        };

        timer.schedule(cancelTask, duration);
    }

    private void showUI(final CharSequence text) {
        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                doShow(text);
            }
        });
    }

    private void hideUI(final CharSequence text) {
        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                doHide(text);
            }
        });
    }

    private void doShow(CharSequence text) {
        mView.setText(text);
        mView.setVisibility(View.VISIBLE);
    }

    private void doHide(CharSequence text) {
        mView.setText(text);
        mView.setVisibility(View.INVISIBLE);
    }
}

  

以上是关于Android开发之《实现类似Toast可以自动消失的提示栏Tip》的主要内容,如果未能解决你的问题,请参考以下文章

Android开发之Toast

Android开发基础之消息提示组件Toast

Android开发基础之消息提示组件Toast

Android之Toast通知的几种自定义用法

android自定义Toast之-弹出消息

iOS开发:Toast for iPhone