繁体   English   中英

如何传递上下文?

[英]How to pass 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);
}

}

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

class GlobalClass extends Application {

  public static Context context;

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

  }

第二,你需要在AndroidManifest.xml里面的应用程序标签中设置这个类
像这样:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM