OnSharedPreferenceChangeListener

时间:2018-10-17 14:04:47

标签: android sharedpreferences

_

大家好,

我创建了一个简单的应用,其中包含1个活动和2个片段(ViewPager)。 片段1包含9个按钮。

  • 3个用于更改背景颜色(红色,蓝色,绿色)的按钮
  • 3个用于设置文本字符串nr的按钮。 (1、2 3)
  • 用于3种模式(A,B,C)的3个按钮

片段2仅包含1个TextView,而片段1的按钮对其进行了修改。

按下片段1的按钮后,片段2的TextView就会刷新。

示例: 我处于模式A,然后按红色和字符串1 然后我切换到模式B并选择蓝色和字符串2。 在模式C中,我选择绿色和字符串3。 现在,当切换回模式A时,片段2的TextView为红色和1。

一切正常,但是当按下模式按钮时,textview不会刷新。 我总是必须将观点从自然状态改变为景观状态,反之亦然。

当我单击Nr时。或颜色,我会立即看到变化。 似乎OnPreferenceChangeListener不能识别模式按钮的单击,而其他按钮则单击。

该怎么办?

片段1:

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import static android.content.Context.MODE_PRIVATE;

public class Fragment1 extends Fragment
{
    Button buttonModeA, buttonModeB, buttonModeC, buttonRed, buttonBlue, buttonGreen, buttonNr1, buttonNr2, buttonNr3;
    TextView textViewNr;
    String mode, text;
    int bColor; // Background color for textview
    SharedPreferences prefsMode; // Specific SharedPreferences (modes)

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View fragmentOne = inflater.inflate(R.layout.fragment1, container, false); // Link view and layout
        buttonModeA = fragmentOne.findViewById(R.id.button_load_a);
        buttonModeB = fragmentOne.findViewById(R.id.button_load_b);
        buttonModeC = fragmentOne.findViewById(R.id.button_load_c);
        buttonRed = fragmentOne.findViewById(R.id.button_red);
        buttonBlue = fragmentOne.findViewById(R.id.button_blue);
        buttonGreen = fragmentOne.findViewById(R.id.button_green);
        buttonNr1 = fragmentOne.findViewById(R.id.button_nr_1);
        buttonNr2 = fragmentOne.findViewById(R.id.button_nr_2);
        buttonNr3 = fragmentOne.findViewById(R.id.button_nr_3);

        loadModeAndSettings(); // Load SharedPreferences
        buttonModeA.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                mode = "A"; // Set mode to A
                saveMode(); // Save selected mode
                loadModeAndSettings();
            }
        });
        buttonModeB.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                mode = "B"; // Set mode to B
                saveMode(); // Save selected mode
                loadModeAndSettings();
            }
        });
        buttonModeC.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                mode = "C"; // Set mode to C
                saveMode(); // Save selected mode
                loadModeAndSettings();
            }
        });
        buttonRed.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                bColor = getResources().getColor(R.color.red); // Set background color to red
                saveSettings(); // Save settings
            }
        });
        buttonBlue.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                bColor = getResources().getColor(R.color.blue); // Set background color to blue
                saveSettings(); // Save settings
            }
        });
        buttonGreen.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                bColor = getResources().getColor(R.color.green); // Set background color to green
                saveSettings(); // Save settings
            }
        });
        buttonNr1.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                animationEffect(buttonNr1); // Start animation for this button
                text = "1"; // Set text to 1
                saveSettings(); // Save settings
            }
        });
        buttonNr2.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                text = "2"; // Set text to 2
                saveSettings(); // Save settings
            }
        });
        buttonNr3.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                text = "3"; // Set text to 3
                saveSettings(); // Save settings
            }
        });
        return fragmentOne;
    }
    public void saveMode()
    {
        SharedPreferences prefs = getActivity().getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE); // Create new SharedPreferences instance
        SharedPreferences.Editor editor = prefs.edit(); // Create access variable for editor
        editor.putString("mode", mode); // Put received value for mode into editor
        editor.apply(); // Save + close instance
    }
    public void saveSettings()
    {
        SharedPreferences prefsMode = getActivity().getSharedPreferences("MY_SHARED_PREF_"+mode, MODE_PRIVATE); // Create new SharedPreferences instance for selected mode
        SharedPreferences.Editor editorMode = prefsMode.edit(); // Create access variable for editor
        editorMode.putInt("bColor", bColor); // Put received value into editor
        editorMode.putString("text", text); // Put received value into editor
        editorMode.apply(); // Save + close instance
    }
    public void loadModeAndSettings()
    {
        SharedPreferences prefs = getActivity().getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE); // Load saved shared file
        mode = prefs.getString("mode", "A"); // mode or default value: A
        prefsMode = getActivity().getSharedPreferences("MY_SHARED_PREF_"+mode, MODE_PRIVATE); // Retrieve current prefsMode
        bColor = prefsMode.getInt("bColor", 0); // Load value of background color or default value
        text = prefsMode.getString("text", "default"); // Load value of text string or default value
    }
}

片段2:

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import static android.content.Context.MODE_PRIVATE;

public class Fragment2 extends Fragment
{
    TextView textViewNr; // Visual feedback for color and nr.
    String mode, text; // Mode for SharedPreferences and text nr. for textViewNr
    int bColor; // Background color for textView
    SharedPreferences prefsMode; // Specific SharedPreferences (modes)
    private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener; // Access variable for SharedPreferencesChangeListener

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View fragmentTwo = inflater.inflate(R.layout.fragment2, container, false); // Link view and layout
        textViewNr = fragmentTwo.findViewById(R.id.text_view_nr); // Link variable to ID
        loadModeAndSettings(); // Load SharedPreferences
        preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() // Check if SharedPreferences have been changed
        {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
            {
                loadModeAndSettings(); // Load settings and refresh views if anything has been changed
            }
        };
        prefsMode.registerOnSharedPreferenceChangeListener(preferenceChangeListener); // Apply changes
        return fragmentTwo;
    };
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (preferenceChangeListener != null)
        {
            prefsMode.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
        }
    }
    public void loadModeAndSettings() // Load mode and its settings
    {
        SharedPreferences prefs = getActivity().getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE); // Load saved shared file
        mode = prefs.getString("mode", "A"); // mode or default value: A
        prefsMode = getActivity().getSharedPreferences("MY_SHARED_PREF_"+mode, MODE_PRIVATE); // Retrieve current prefsMode
        bColor = prefsMode.getInt("bColor", 0); // Load value of background color or default value
        text = prefsMode.getString("text", "default"); // Load value of text string or default value
        updateGui(); // Update all views
    }
    public void updateGui() // Refresh views
    {
        textViewNr.setBackgroundColor(bColor); // Update background color of textViewMode
        textViewNr.setText(text); // Update text of textViewMode
    }
}

感谢您的帮助!

最诚挚的问候

1 个答案:

答案 0 :(得分:0)

_ 专家您好,

我通过利用漏洞解决了这个问题。

我只是添加了一个DummyActivity,它在被调用时立即关闭。

在fragment1中单击模式按钮后,我创建了一个旨在通过更新现有的saveMode方法来启动DummyActivity的意图。

(我没有感觉到或看到此RunActivity / Close Activity过程的任何内容-至少在模拟器上如此。)

在Fragment2中,我将95%的代码(位于onCreateView中)移到了onResume中。

好吧,它运作完美!

P.S。不过,也许有更清洁的解决方案。

最诚挚的问候