我想将主要活动的上下文传递给另一个类以创建 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);
}
}
首先,您需要静态变量在应用程序类中声明全局变量,
像这样
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)