如何传递上下文? [英] How to pass context?

查看:88
本文介绍了如何传递上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将主要活动的上下文传递给另一个类,以创建Toast.

I want to pass the context of the main activity to another class in order to create a Toast.

我的主要活动是调用一个将删除文件的类.如果文件不存在,则删除文件的类将调用Toast.

My main activity calls a class that will delete a file. The class that deletes files will call a toast if the file does not exist.

这是我的代码:

public class MyActivity extends AppCompatActivity
{
    public void onCreate(Bundle savedInstanceState)
    {
     // create a file

    Button buttoncreate = (Button)findViewById(R.id.create_button);

    Button buttondelete = (Button)findViewById(R.id.delete_button);
    ...

    buttondelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            new DeleteFile();
        }
    });
}

public class DeleteFile extends AsyncTask {

@Override
public  Object doInBackground(Object[] params) {
    File root = android.os.Environment.getExternalStorageDirectory();
    File dir = new File(root.getAbsolutePath() + "/mydir");
    if (!(dir.exists())) {
        CharSequence text = "Files do not exist!";
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(getApplicationContext(), text, duration);
        toast.show();

    } else {
        File file;
        file = new File(dir, "mydata.bmp");
        file.delete();
    }
    return(1);
}

}

推荐答案

首先,您需要使用静态变量在应用程序类中声明全局变量,
像这样

First thing, you need Static Variable to declare global variable in Application Class,
like this

class GlobalClass extends Application {

  public static Context context;

   @Override
    public void onCreate() {
    super.onCreate();
    context = getApplicationContext();
    }

  }

您需要在应用程序标记内的AndroidManifest.xml中设置此类
像这样:

second you need set this class in AndroidManifest.xml inside application tag
like this:

<application
    android:name=".GlobalClass"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar" >

然后,在需要访问此数据的任何地方,均可通过以下方式获取Application对象:

then whereever you need to access this data, get Application object by:

 Toast toast = Toast.makeText(GlobalClass.context, text, duration);
    toast.show();

这篇关于如何传递上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆