【发布时间】:2015-02-19 01:21:38
【问题描述】:
所以我从THIS TUTORIAL 学习了如何使用 FragmentActivity 在 Android 中制作标签。所以现在我有一个包含 3 个选项卡的 FragmentActivity,这意味着这些选项卡中有三个不同的 Fragment。
FragmentActivity 类
public class ProductSingle_Activity extends FragmentActivity {
ViewPager Tab;
public TabPagerAdapter TabAdapter;
ActionBar actionBar;
Context ctx = this;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_single);
.... and so on
我有两个 Fragment 成为 FragmentActivity 的两个选项卡:
一个片段:
public class details_frag_activity extends Fragment {
Context ctx;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.details_frag, container, false);
}
}
所以我在应用程序的 SharedPreferences 中存储了一些信息,例如“名称”和“描述”。
SharedPreferences pref = ctx.getSharedPreferences("product_details", 0);
//ctx being the context
Editor editor = pref.edit();
editor.putString("pname", name);
editor.commit();
我想通过这样的片段之一访问这些信息:
public class details_frag_activity extends Fragment {
Context ctx;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.details_frag, container, false);
SharedPreferences pref = ctx.getSharedPreferences("product_details", 0);
//I cant access the ctx (Context). To avoid the error I just declared a local variable. I need to get the context of the FragmentActivity
String pname = pref.getString("pname", null);
但是我无法通过片段访问“ctx”(上下文)。有没有办法将 FragmentActivity 的上下文传递给 Fragment 类,以便它们可以从 SharedPreferences 中检索存储的信息?或者有没有更好的方法通过片段(标签)访问公共信息?
【问题讨论】:
-
是我的答案。
标签: java android android-fragments tabs sharedpreferences