12 消息提示toast 和Context

Toast

toast用于向用户显示一些帮助和提示;

特点:

   1、没有焦点。

   2、显示时间有限,会自动消失。

案例:

Test_toastActivity.java:

public class Test_toastActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    public void test1(View view){
        Toast.makeText(this.getApplicationContext(), "hello toast.....", 1).show();
        //Toast.LENGTH_LONG也可表示1;Toast.LENGTH_SHORT也可表示0
        //第一个参数也可以写成this,如:Toast.makeText(this, "hello toast.....", 1).show();
        /*
         * this --> activity --> Context
         * this.getApplicationContext --> Context
         * 
         */
     /*
         * Activity Context --> request
         * ApplicationContext --> Application
         */

    }
}

运行结果:


Context ApplicationContext的比较:

    Context提供了关于应用环境全局信息的接口。它是一个抽象类,它的实现由Android系统所提供。通过context我们可以加载资源,获取android系统提供的一些服务类

android 当真一般有两种context:

1、application Context;

2、Activity Context;

Application Context:application和周围系统进行沟通的对象,生命周期长。

Activity Context:activity和周围的activity 或者周围应用程序沟通的对象,生命周期短。


Application ContextActivity Context使用时候的选择:

什么时候想让对象的生命周期和进程关联起来,就用Application Context,,可以使对象存存活久一点;如果想让对象用完就不用就用Activity Context

一般用Application Context都可以。

然而如果你所有的地方都使用Application Context,并且你忘了手动把它销毁的话,会导致内存泄漏。


通过设置参数,来改变显示位置:

Test_toastActivity.java:

public class Test_toastActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    public void test1(View view){
        
        //Toast.makeText(this.getApplicationContext(), "hello toast.....", 1).show();
        //可以改变toast的显示方法:
        Toast toast=Toast.makeText(this.getApplicationContext(), "hello toast.....", 1);
        toast.setGravity(Gravity.CENTER, 100, 0);//后两个参数表示X轴和Y轴的偏移量;
        toast.show();
        //Toast.LENGTH_LONG也可表示1;Toast.LENGTH_SHORT也可表示0
        //第一个参数也可以写成this,如:Toast.makeText(this, "hello toast.....", 1).show();
    }
}

运行结果:

原文地址:https://www.cnblogs.com/cxm-weiniss/p/7205245.html