S
S
Shinso2015-06-04 18:48:13
Android
Shinso, 2015-06-04 18:48:13

How to store a number in a fragment and display it the next time it is run?

In general, there is a Fragment with a text field, and a button, when pressed, the number increases by one, I want to make it so that the number is remembered in the counter when exiting, and appears the next time I enter it, but I can’t figure out how to do it in the fragment.

public class fragment_main extends Fragment {

    private int fCount = 0;
    TextView mFoodTextView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);


        mFoodTextView = (TextView) rootView.findViewById(R.id.textView42);
        Button mFoodCounterButton = (Button) rootView.findViewById(R.id.button2);
        mFoodCounterButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mFoodTextView.setText(getString(R.string.Food) + " " + ++fCount);
            }
        });

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Emin, 2015-06-04
@Shinso

Use SharedPreferences . You need to save fCount before exit (for example in onStop) and read back on creation (in onCreateView).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question