簡體   English   中英

片段中onclick的Android SharedPreferences

[英]Android SharedPreferences from onclick in a fragment

我希望有人能給我一些指導,說明如何從onViewCreated事件中定義的按鈕的onclick事件中訪問SharedPreferences。

我可以通過調用以下內容來設置onViewCreated事件中接口的值:

SharedPreferences prefs = this.getActivity().getSharedPreferences(
    "com.example.app", Context.MODE_PRIVATE);

並獲得適當的值,但是我在界面上有一個按鈕可以按以保存更改,而我似乎無法想出從我的按鈕的click事件中訪問SharedPreferences的正確方法:

Button btn = (Button)view.findViewById(R.id.btnSave);
btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Perform action on click
        Log.d("test","here");
        SharedPreferences prefs = this.getActivity().getSharedPreferences(
                "com.example.app", Context.MODE_PRIVATE);

    }
});

該代碼顯然不起作用,因為這里是指視圖,而getActivity不能從視圖中起作用。 誰能告訴我如何從此處訪問活動,以便隨后可以訪問SharedPreferences?

嗨,歡迎來到StackOverflow。

之所以不能訪問SharedPreferences是因為this 不是片段:如果仔細觀察,您會發現您有2個嵌套上下文 ,因此this實際上是一個OnClickListener對象(位於片段內部)。

當您需要訪問“父上下文”時 ,您可以這樣進行:

 public class MyCoolFragment extends Fragment {

    // here "this" is in fact your Fragment,
    // so this.getActivity().getSharedPreferences() DOES exist

    .
    .
    .

    Button btn = (Button)findViewById(R.id.btnSave);
    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            // Perform action on click
            // "this" is NO LONGER your fragment, but the View.OnClickListener
            // to access the PARENT CONTEXT you prepend the CLASS NAME:

            // MyCoolFragment.this.getActivity().getSharedPreferences will work:


            SharedPreferences prefs = MyCoolFragment.this.getActivity().getSharedPreferences()
                    "com.example.app", Context.MODE_PRIVATE);

        }
    });

這是非常典型的Java中有深層嵌套的背景下,所以你必須要告訴Java的什么this你想要的。

另外,請記住, 您可以輕松地從ANY VIEW獲取上下文。 ,因此在點擊處理程序中,您還可以執行以下操作:

        Button btn = (Button)view.findViewById(R.id.btnSave);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                Activity myActivity=(Activity)(v.getContext()); // all views have a reference to their context
                SharedPreferences prefs =myActivity.getSharedPreferences(
                        "com.example.app", Context.MODE_PRIVATE);

            }
        });

希望能幫助到你 !

您是否嘗試過僅使用getActivity()。getSharedPreferences()?

SharedPreferences prefs = getActivity().getSharedPreferences(
            "com.example.app", Context.MODE_PRIVATE);

注意:由於我的聲譽低下,不能問這個問題。

哥,很簡單 只需從片段中查看我的代碼即可。 你會知道怎么做

   SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
   return sharedPreferences.getString(key, "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM