Vishak A Kamath
Vishak A Kamath

Reputation: 137

Retain text in a TextView on rotation

I have two fragments TestOneFragment which is the default one and TestTwoFragment, which is added to the back stack. When I rotate the screen when TestTwoFragment is in foreground, the text should also remain the same.

This is the onCreateView method in my Fragment

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    viewHolder = inflater.inflate(R.layout.fragment_test_two, container, false)

    arguments?.getString("msg").run {
        if (this != null)
            viewHolder.tvFragTestTwo.text = this
        else
            viewHolder.tvFragTestTwo.text = "NO BUTTONS CLICKED"
    }

    listener.onCreateListener(viewHolder.tvFragTestTwo.text.toString())

    return viewHolder
}

I've created an interface OnCreateListener so that i can use the textView in the Parent Activity. This is the implementation of that interface.

override fun onCreateListener(string: String) {
    val bundle = Bundle()
    bundle.putString("msg", string)
    testTwoFragment.arguments = bundle
}

Everytime the screen is rotated, The text is set to the default value.

Upvotes: 1

Views: 922

Answers (2)

Vishak A Kamath
Vishak A Kamath

Reputation: 137

I added android:configChanges="orientation|screenSize" within the respective activity tag inside the manifest file and it worked for me.

Upvotes: 1

Nicola Gallazzi
Nicola Gallazzi

Reputation: 8705

Every time you rotate the screen Android destroys and recreates the activity bound to your fragment. In order to keep the text in the text view you shoud save your information in onSaveInstanceState method and restore the saved information in the onActivityCreated method.

public class MainFragment extends Fragment {

    // These variable are destroyed along with Activity
    private String text;

    ...

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("your_text_id", text); // this text comes from your textview
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        text = savedInstanceState.getString("your_text_id");
    }

}

Upvotes: 0

Related Questions