扩展 MaterialButton:应该做吗? SavedState 具有包可见性

Extending MaterialButton: Should it be done? SavedState has package visibility

我已经扩展了 MaterialButton 以在单击时在按钮上显示一致的加载状态,但是我 运行 在实现 SavedState 恢复时遇到了一个小问题。

我写的这个进度按钮变体,禁用视图,显示动画加载微调器,可选择显示加载文本和恢复,然后在启用视图时恢复之前显示的 text/state。

MaterialButton.SavedState 是包私有的,因此不能在外部扩展。这不会对我的实现造成问题,因为我不使用它扩展的 'checked' 字段,但它确实提出了这些问题:

TLDR

material-components-android:1.2.0

Is it wrong to extend this MaterialButton?

MaterialButton 不是最终的 class 那么您 可以 扩展它,例如 ExtendedFloatingActionButton 扩展它。

If not would it be appropriate to submit a PR to the public repo to make SavedState public?

您不需要 MaterialButton.SavedState public。你可以这样做:

public class MyButton extends MaterialButton
{
    private String text;

    //....


    static class SavedState extends AbsSavedState {
        @Nullable CharSequence myText;

        SavedState(Parcelable superState) {
            super(superState);
        }

        SavedState(@NonNull Parcel source, ClassLoader loader) {
            super(source, loader);
            myText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
        }

        @Override
        public void writeToParcel(@NonNull Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            TextUtils.writeToParcel(myText, dest, flags);
        }

        @NonNull
        @Override
        public String toString() {
            return "MyButton.SavedState{"
                    + " text="
                    + myText
                    + "}";
        }

        public static final Creator<SavedState> CREATOR =
                new ClassLoaderCreator<SavedState>() {
                    @NonNull
                    @Override
                    public SavedState createFromParcel(@NonNull Parcel in, ClassLoader loader) {
                        return new SavedState(in, loader);
                    }

                    @Nullable
                    @Override
                    public SavedState createFromParcel(@NonNull Parcel in) {
                        return new SavedState(in, null);
                    }

                    @NonNull
                    @Override
                    public SavedState[] newArray(int size) {
                        return new SavedState[size];
                    }
                };
    }

    @Nullable
    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);
        ss.myText = text;
        return ss;
    }

    @Override
    public void onRestoreInstanceState(@Nullable Parcelable state) {
        if (!(state instanceof SavedState)) {
            super.onRestoreInstanceState(state);
            return;
        }
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());
        text = ss.myText.toString();
    }
}

这样 MyButton.SavedState 也将包含 MaterialButton.SaveState 而无需扩展它。