单击按钮即可更新/刷新片段

时间:2018-09-19 12:23:15

标签: android android-fragments

我创建了一个非常简单的测试应用,其中包括:

  • 2个片段
  • 2个按钮(在片段1中)
  • 1个文本视图(在片段2中)
  • 两个片段的
  • SharedPreferences
  • 一个ViewPager,可让您从片段1滑动到片段2,反之亦然

我的目标是每次我点击片段1中的特定按钮时, 片段2的文本视图已更新。

这可行,但是,我总是必须首先旋转显示器,以便刷新片段/视图。

我在这里找到了一些线程,但是似乎有很多不同的方式。

据我了解,一种方法是分离片段2,对其进行更新,然后再次附加。

问题是:

我是否还必须修改片段2的代码,还是足以修改方法 片段1中的savePreferences?

MainActivity:

        import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import java.util.ArrayList;
    import java.util.List;
    public class MainActivity extends AppCompatActivity
    {
        ViewPager vp; // Variable for Viewpager
        private static final String TAG = "MainActivity"; // Not sure if needed

        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ViewPager vp = findViewById(R.id.vp); // Link variable to ID
            SetUpViewPager(vp); // Run method
        }
        public void SetUpViewPager(ViewPager viewpage)
        {
            MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
            Adapter.AddPageFragment(new Fragment1(), "Fragment1"); // Load page 1 inside of ViewPager
            Adapter.AddPageFragment(new Fragment2(), "Fragment2"); // Load page 1 inside of ViewPager
            viewpage.setAdapter(Adapter);
        }
        public class MyViewPagerAdapter extends FragmentPagerAdapter
        {
            private List<Fragment> MyFragment = new ArrayList<>();
            private List<String> MyPageTitle = new ArrayList<>();

            public MyViewPagerAdapter(FragmentManager manager)
            {
                super(manager);
            }
            public void AddPageFragment(Fragment Frag, String Title)
            {
                MyFragment.add(Frag);
                MyPageTitle.add(Title);
            }
            @Override
            public Fragment getItem(int i)
            {
                return MyFragment.get(i);
            }
            @Nullable
            @Override
            public CharSequence getPageTitle(int position)
            {
                return MyPageTitle.get(position);
            }
            @Override
            public int getCount()
            {
                return 2; // 2 pages total
            }
        }
    }

Fragment1:

        import android.content.Context;
    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.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.TextView;
    public class Fragment1 extends Fragment
    {
        @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
            Button button1 = fragmentOne.findViewById(R.id.button_1); // Link variable to ID
            Button button2 = fragmentOne.findViewById(R.id.button_2); // Link variable to ID
            button1.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    savePreferences("1");
                }
            });
            button2.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    savePreferences("2");
                }
            });
            return fragmentOne;
        }
        public void savePreferences(String text)
        {
            SharedPreferences prefs = getActivity().getSharedPreferences("MY_SHARED_PREF", Context.MODE_PRIVATE); // Create new SharedPreferences instance
            SharedPreferences.Editor editor = prefs.edit(); // Create variable for SharedPreferences
            editor.putString("text", text); // Write text coming from button inside of editor
            editor.apply(); // Apply and close SharedPreferences instance
            Log.wtf("Text is: ", text); // Check if text is correct - yes, it's correct
        }
    }

Fragment2:

        import android.content.Context;
    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;
    public class Fragment2 extends Fragment
    {
        String text; // Text which gets shown inside of TextView
        @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
            loadSharedPreferences(); // Load SharedPreferences
            TextView textViewValue = fragmentTwo.findViewById(R.id.text_view); // Link variable to ID
            textViewValue.setText(text); // Show loaded value
            return fragmentTwo;
        }
        public void loadSharedPreferences()
        {
            SharedPreferences prefs = getActivity().getSharedPreferences("MY_SHARED_PREF", Context.MODE_PRIVATE); // Load SharedPreferences
            text = prefs.getString("text", "0"); // Retrieve text from Shared Preferences
        }
    }

修改-20.09.18 Fragment2的第三版:

        import android.content.Context;
    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;

    public class Fragment2 extends Fragment
    {
        String text;
        private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;
        private static final String STATE_TEXT = "state_text";
        SharedPreferences prefs;

        @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
            final TextView textViewValue = fragmentTwo.findViewById(R.id.text_view); // Link variable to ID
            prefs = getActivity().getSharedPreferences("MY_SHARED_PREF", Context.MODE_PRIVATE);
            preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()
            {
                @Override
                public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
                {
                    switch (key)
                    {
                        case "text":
                            String text = sharedPreferences.getString("text", "0");
                            textViewValue.setText(text);
                        break;
                    }
                }
            };
            prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
            return fragmentTwo;
        };
        @Override
        public void onSaveInstanceState(Bundle outState)
        {
            super.onSaveInstanceState(outState);
            outState.putString(STATE_TEXT, text);
        }
        @Override
        public void onViewStateRestored(Bundle savedInstanceState)
        {
            super.onViewStateRestored(savedInstanceState);
            text = savedInstanceState.getString(STATE_TEXT);
        }
        @Override
        public void onDestroy()
        {
            super.onDestroy();
            if (preferenceChangeListener != null)
            {
                prefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
            }
        }
    }

编辑-24.09.18

Fragment1:

        import android.content.Context;
    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.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.TextView;
    public class Fragment1 extends Fragment
    {
        String text;
        int bColor;
        SharedPreferences prefs;
        @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
            Button button1 = fragmentOne.findViewById(R.id.button_1); // Link variable to ID
            Button button2 = fragmentOne.findViewById(R.id.button_2); // Link variable to ID
            Button buttonColorRed = fragmentOne.findViewById(R.id.button_color_red); // Link variable to ID
            Button buttonColorBlue = fragmentOne.findViewById(R.id.button_color_blue); // Link variable to ID
            prefs = getActivity().getSharedPreferences("MY_SHARED_PREF", Context.MODE_PRIVATE);
            bColor = prefs.getInt("bcolor", 0);
            text = prefs.getString("text", "0");
            button1.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    text = "1";
                    savePreferences();
                }
            });
            button2.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    text = "2";
                    savePreferences();
                }
            });
            buttonColorRed.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    bColor = getResources().getColor(R.color.red);
                    savePreferences();
                }
            });
            buttonColorBlue.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    bColor = getResources().getColor(R.color.blue);
                    savePreferences();
                }
            });
            return fragmentOne;
        }
        public void savePreferences()
        {
            SharedPreferences prefs = getActivity().getSharedPreferences("MY_SHARED_PREF", Context.MODE_PRIVATE); // Create new SharedPreferences instance
            SharedPreferences.Editor editor = prefs.edit(); // Create variable for SharedPreferences
            editor.putString("text", text); // Write text coming from button inside of editor
            editor.putInt("bcolor", bColor); // Write background color coming from button inside of editor
            editor.apply(); // Apply and close SharedPreferences instance
            Log.wtf("Text is: ", text); // Check if text is correct - yes, it's correct
        }
    }

Fragment2:

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

    public class Fragment2 extends Fragment
    {
        String text;
        int bColor;
        private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;
        SharedPreferences prefs;
        @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
            final TextView textViewValue = fragmentTwo.findViewById(R.id.text_view); // Link variable to ID
            final ConstraintLayout constraintLayout = fragmentTwo.findViewById(R.id.constraint_layout);
            prefs = getActivity().getSharedPreferences("MY_SHARED_PREF", Context.MODE_PRIVATE);
            text = prefs.getString("text", "0");
            textViewValue.setText(text);
            bColor = prefs.getInt("bcolor", 0);
            constraintLayout.setBackgroundColor(bColor);
            preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()
            {
                @Override
                public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
                {
                    switch (key)
                    {
                        case "text":
                            text = sharedPreferences.getString("text", "0");
                            textViewValue.setText(text);
                        case "bcolor":
                            bColor = sharedPreferences.getInt("bcolor", getResources().getColor(R.color.white));
                            constraintLayout.setBackgroundColor(bColor);
                        break;
                    }
                }
            };
            prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
            return fragmentTwo;
        };
        @Override
        public void onDestroy()
        {
            super.onDestroy();
            if (preferenceChangeListener != null)
            {
                prefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
            }
        }
    }

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

要取消注册您的侦听器,请使其成为全局变量。请尝试以下:

import android.content.Context;
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;

public class Fragment2 extends Fragment {

    String text;
    private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;
    SharedPreferences prefs;

    @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

        final TextView textViewValue = fragmentTwo.findViewById(R.id.text_view); // Link variable to ID

        prefs = getActivity().getSharedPreferences("MY_SHARED_PREF", Context.MODE_PRIVATE);

        preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                switch (key)
                {
                    case "text":
                        String text = sharedPreferences.getString("text", "0");
                        textViewValue.setText(text);
                    break;
                }
            }
        };

        prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
        return fragmentTwo;
    };

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (preferenceChangeListener != null){
            prefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
        }
    }
}

请注意,Fragment2被销毁时,监听器将被注销。通常,当布局中有三个片段并且您进入第3个标签时,除非您在ViewPager中增加了屏幕外页面,否则第一个标签片段将被销毁。

要解决此问题,请从SharedPreference的{​​{1}}中的onCreateView将文本设置为您的文本视图,以便在ViewPager中重新加载文本时进行更新。您现在不会注意到问题,但是如果您在ViewPager中添加另一个选项卡,可能会出现问题,这就是解决方案。