如何传递上下文?

G.V*_*.V. 5 android android-context

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

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

这是我的代码:

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);
}

}
Run Code Online (Sandbox Code Playgroud)

小智 6

首先,您需要静态变量来在Application Class中声明全局变量,
就像这样

class GlobalClass extends Application {

  public static Context context;

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

  }
Run Code Online (Sandbox Code Playgroud)

第二,你需要在AndroidManifest.xml中的应用程序标签中设置这个类,
如下所示:

<application
    android:name=".GlobalClass"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar" >
Run Code Online (Sandbox Code Playgroud)

然后,当您需要访问此数据时,通过以下方式获取Application对象:

 Toast toast = Toast.makeText(GlobalClass.context, text, duration);
    toast.show();
Run Code Online (Sandbox Code Playgroud)

  • 很高兴看到有人真正帮助OP,而不是粗鲁. (6认同)