[英]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.