Reset Android Button To Default Color And Style
In my app I need to be able to change the background color of a button and back to the default color. Changing the color to a custom color works, but my code for reversing the proc
Solution 1:
when u set background in second time set it by getting background from another button which has the default background so for ex let's say button in red is b1 and button in default is b2
Then code to set background for b1 to become default is
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
b1.setBackground(b2.getBackground());
else b1.setBackgroundDrawable(b2.getBackground());
Solution 2:
It took some time because many of the answers included deprecated code, but I have a solution to my issue. Using the suggestion of Mohamed I grabbed the default Drawable value of one of the buttons and stored it. The biggest issue was finding a way for both the default color and my color from colors.xml to be the same type for my ternary if to work.
privateDrawable mDefaultButtonColor;
privateDrawable mSelectedButtonColor;
publicViewonCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mNomButton = (Button) view.findViewById(R.id.custom_practice_nom_button);
mNomButton.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View view) {
mNomIsSelected = toggleButton(mNomButton, mNomIsSelected);
}
}
mDefaultButtonColor = ((Drawable) mNomButton.getBackground());
mSelectedButtonColor = ContextCompat.getDrawable(getActivity(), R.color.buttonSelected);
return view;
}
privatebooleantoggleButton(Button button, boolean isSelected) {
isSelected = !isSelected;
button.setBackground(isSelected ? mSelectedButtonColor : mDefaultButtonColor);
return isSelected;
}
Post a Comment for "Reset Android Button To Default Color And Style"