zoukankan      html  css  js  c++  java
  • 在Activity/Fragment以外使用Toast【转】

    在 Activity 使用 Toast

    这种是最基本的使用,Toast的第一个参数就是Context,一般在Activity中我们直接用this代替,代表调用者的实例为Activity。

    public class TestDBActivity extends Activity {
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.testdb2);
            
            Toast.makeText(this, "欢迎来到简明现代魔法~", Toast.LENGTH_SHORT).show();
            //Toast.makeText(getApplicationContext(), "欢迎来到简明现代魔法~", Toast.LENGTH_SHORT).show();
        }
    }

    这里用 getApplicationContext() 代替 this 也是可以的。

    而到了一个button的onClick(View view)等方法时,我们用this时就会报错,所以我们可能使用ActivityName.this来解决,主要原因是因为实现Context的类主要有Android特有的几个模型,Activity、Service以及BroadcastReceiver。

    在 Fragment 使用 Toast

    在 Fragment 里需要用 getActivity() 来获取 Context 对象,写法如下:

    public class BlogFragment extends Fragment {
        
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            
            Toast.makeText(getActivity(), "欢迎来到简明现代魔法~", Toast.LENGTH_SHORT).show();
        }
    )

    在非 Activity/Fragment 使用 Toast

    如果你想在非 Activity/Fragment 的某个 class 中用 Toast,你还是用 this/getApplicationContext() 的话,一般会报这么一个错误:

    the method getApplicationContext() is undefined

    因为获取不到上下文,那么如何在这个class中也获取到 Context 呢?可以将 Context 传递过去。

    在实例化一个 class 的时候,将 Context 作为参数传递:

    MyClass myClass = new MyClass(this);

    然后写一个构造函数,用以接收 Context 作为一个参数。

    public class MyClass 
    {
        Context c;
        public MyClass(Context context)
        {
             c = context;
         }
    }

    接下来就可以使用 Toast 了:

    public void onProviderDisabled(String provider) {
        Toast.makeText(c, "Gps Disabled", Toast.LENGTH_SHORT);
    }

    转自:现代魔法学院

  • 相关阅读:
    2
    作业5
    实验十
    作业 5 指针应用
    九九乘法表
    实验七(课堂练习)
    实验六 数组 (2)
    实验六 数组
    课堂实验5(求从m到n之间(包括m和n)所有素数的和)
    课堂实验5-2
  • 原文地址:https://www.cnblogs.com/xs104/p/4925620.html
Copyright © 2011-2022 走看看