【问题标题】:How to pass context?如何传递上下文?
【发布时间】:2016-11-30 15:43:33
【问题描述】:

我想将主要活动的上下文传递给另一个类以创建 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);
}

}

【问题讨论】:

  • 我使用 doinbackgroud... 在创建类的过程中如何传递值?
  • 不确定为什么有人对您的问题投了反对票。但是,我相信他们比我们其他人聪明得多。我已经弥补了。

标签: android android-context


【解决方案1】:

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

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

【讨论】:

  • 很高兴看到有人真正帮助 OP,而不是粗鲁。
猜你喜欢
  • 1970-01-01
  • 2011-10-27
  • 2018-12-28
  • 2015-06-29
  • 2015-06-17
  • 1970-01-01
  • 2021-12-19
  • 2014-12-16
  • 2011-04-07
相关资源
最近更新 更多