setRetainInstance not retaining the instance

前端 未结 1 685
独厮守ぢ
独厮守ぢ 2020-12-10 18:18

I\'m trying to use setRetainInstance() but it seems not working for me! =(. I simplified the problem to the easiest version:

I have a fragment with a TextView and a

相关标签:
1条回答
  • 2020-12-10 18:57

    You are missing that onCreateView runs after the rotation again and inflates the default view with the default text again.

    You need to restore the state of your views manually, e.g.:

    public class SayHelloFragment extends Fragment {
    
        private String mText;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.say_hello_layout, container);
            final TextView text = (TextView) view.findViewById(R.id.textView1);
            if (mText != null)
                text.setText(mText);
    
            view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    mText = "Hello!";
                    text.setText(mText);
                }
            });
            return view;
        }
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            setRetainInstance(true);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题