[英]Android: Using SharedPreferences with a Tab Layout
因此,我從THIS TUTORIAL了解了如何使用FragmentActivity在Android中制作標簽。 所以現在我有了一個FragmentActivity,其中包含3個選項卡,這意味着在這些選項卡中是三個不同的Fragments。
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
我有兩個Fragments成為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中檢索存儲的信息? 還是有更好的方法通過片段(Tab)訪問公共信息?
您可以在details_frag_activity
重寫onAttach
方法,並在details_frag_activity
類內創建ProductSingle_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);
如上一個答案所述,您可以簡單地使用:
SharedPreferences pref = getActivity().getSharedPreferences("product_details", 0);
在細分類中,可以使用一種方法獲取上下文。
private Activity activity;
@Override
public void onAttach(Activity activity) {
this.activity = activity;
super.onAttach(activity);
}
只需將該方法參數分配給一個字段,然后您就可以在需要的任何位置訪問此活動引用作為上下文。 因為Activity是上下文的子類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.