问题描述
我创建了一个类来从PHP文件中检索JSON编码的注释。此类,从AsyncTask扩展:
I created a class to retrieve comments from a JSON encoding from a PHP file. This class, extends from AsyncTask:
public class RecuperarComentarisFoto extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(????);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
如你所见,我'我试图在doInBackground进程工作时显示ProgressDialog。但是progressDialog构造函数,请求一个Context,我不知道如何提供它。
As you can see, I'm trying to show a ProgressDialog while the "doInBackground" proccess is working. But progressDialog constructor, asks for a Context, and I don't know how to provide it.
我从片段中调用这个类,所以我不能访问这样的上下文:
I'm calling this class from a Fragment, so I can't access the context like this:
pDialog = new ProgressDialog(MyFragmentA.context);
调用主活动:AndroidViewPagerActivity扩展了FragmentActivity。
The "main" acitivity is called: AndroidViewPagerActivity which extends FragmentActivity.
(主要是,我的意思是它是创建标签,并管理它们之间的导航。)
(By main, I mean that it's the one that is creating the tabs, and managing the navigation between them.)
这是它的代码:
public class AndroidViewPagerActivity extends FragmentActivity {
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_HOME);
bar.hide();
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText("Fragment A"), MyFragmentA.class, null);
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
如何访问上下文?我应该使用哪种上下文? AndroidViewPagerActivity上下文?那么如何从片段中访问其上下文?
How can I access the context? Which context should I use? "AndroidViewPagerActivity" context? So how can I access its context from a fragment?
谢谢。
Sergi
推荐答案
在片段$ c中使用
getActivity()
$ c>获取可以传递的 Context
。这是有效的,因为活动
继承自上下文
。
Use getActivity()
inside the Fragment
to obtain a Context
that you can pass along. That works, as Activity
inherits from Context
.
作为替代方案,您可以使用 getApplicationContext()
来获取上下文
。
As alternative you can use getApplicationContext()
to obtain the Context
.
这篇关于从片段中检索上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!