Android:使用带有选项卡布局的SharedPreferences

时间:2014-12-20 05:39:23

标签: java android android-fragments tabs sharedpreferences

因此,我了解了如何使用THIS TUTORIAL中的FragmentActivity在Android中制作标签。所以现在我有一个FragmentActivity,它包含3个标签,这意味着在这些标签中有三个不同的片段。

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的两个标签:

One Fragment:

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

    }
}

所以我存储了一些信息,例如' name'和'描述'在应用程序的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 Classes,以便它们可以从SharedPreferences中检索存储的信息?或者有没有更好的方法通过碎片(标签)访问公共信息?

3 个答案:

答案 0 :(得分:2)

您可以在onAttach中覆盖details_frag_activity方法,并在ProductSingle_Activity课程中创建details_frag_activity对象 用这个......

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    this.activity = (ProductSingle_Activity) activity;
}

或只是尝试

 SharedPreferences pref = getActivity().getSharedPreferences("product_details", 0); 

答案 1 :(得分:2)

如上一个答案中所述,您只需使用:

SharedPreferences pref = getActivity().getSharedPreferences("product_details", 0); 

答案 2 :(得分:1)

在fragement中,使用一种方法可以获得Context。

private Activity activity;
@Override
public void onAttach(Activity activity) {
    this.activity = activity;
    super.onAttach(activity);
}

只需将该方法参数分配给字段,然后您可以根据需要访问此活动参考。因为Activity是Context的子类。

相关问题