Skip to content

Instantly share code, notes, and snippets.

@eungikim
Created February 4, 2021 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eungikim/f66a356f20b67084f348fe2a39b56957 to your computer and use it in GitHub Desktop.
Save eungikim/f66a356f20b67084f348fe2a39b56957 to your computer and use it in GitHub Desktop.
public class ClickerFragment extends Fragment {
public static final String TAG = ClickerFragment.class.getSimpleName();
private SharedPreferences prefs;
private int counter;
private TextView counterText;
private Button up;
private Button reset;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getActivity().getSharedPreferences("counter_alone", Context.MODE_PRIVATE);
counter = prefs.getInt("counter", 0);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container, @NonNull Bundle savedInstanceState) {
View v= inflater. inflate(R.layout.counter_alone, container, false);
counterText = v.findViewById(R.id.counterText);
up = v.findViewById(R.id.up);
reset = v.findViewById(R.id.reset);
up.setOnClickListener(onClickListener);
reset.setOnClickListener(onClickListener);
counterText.setText(counter + "");
return v;
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.up:
counter++;
prefs.edit().putInt("counter", counter).apply();
counterText.setText(counter + "");
break;
case R.id.reset:
counter = 0;
prefs.edit().remove("counter").apply();
counterText.setText(counter + "");
break;
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment