diff options
author | Xin Li <delphij@google.com> | 2019-07-01 20:59:51 +0000 |
---|---|---|
committer | Xin Li <delphij@google.com> | 2019-07-01 20:59:51 +0000 |
commit | aa06a98b9387bf7cda7948de3f3949e82c151856 (patch) | |
tree | d4d0f1ccfa3d6b82ef0a0be0a353328a3001714d /library/main/src/com/android/setupwizardlib | |
parent | f26a9e8e2e422b20c721e199961f11bc82dd250a (diff) | |
parent | 93dacd74efc365bc889773a7cca03adad1ded25d (diff) | |
download | setupwizard-aa06a98b9387bf7cda7948de3f3949e82c151856.tar.gz |
DO NOT MERGE - Merge qt-dev-plus-aosp-without-vendor (5699924) into stage-aosp-mastertemp_140451723
Bug: 134405016
Change-Id: I5e74b54945db4e896b45312ec51d2a4facc01c55
Diffstat (limited to 'library/main/src/com/android/setupwizardlib')
52 files changed, 5674 insertions, 5573 deletions
diff --git a/library/main/src/com/android/setupwizardlib/GlifLayout.java b/library/main/src/com/android/setupwizardlib/GlifLayout.java index 9b30c2f..20fb6b6 100644 --- a/library/main/src/com/android/setupwizardlib/GlifLayout.java +++ b/library/main/src/com/android/setupwizardlib/GlifLayout.java @@ -24,6 +24,9 @@ import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Build.VERSION_CODES; +import androidx.annotation.LayoutRes; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; @@ -32,11 +35,6 @@ import android.view.ViewStub; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.TextView; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - import com.android.setupwizardlib.template.ButtonFooterMixin; import com.android.setupwizardlib.template.ColoredHeaderMixin; import com.android.setupwizardlib.template.HeaderMixin; @@ -50,6 +48,7 @@ import com.android.setupwizardlib.view.StatusBarBackgroundLayout; * Layout for the GLIF theme used in Setup Wizard for N. * * <p>Example usage: + * * <pre>{@code * <com.android.setupwizardlib.GlifLayout * xmlns:android="http://schemas.android.com/apk/res/android" @@ -66,259 +65,254 @@ import com.android.setupwizardlib.view.StatusBarBackgroundLayout; */ public class GlifLayout extends TemplateLayout { - private static final String TAG = "GlifLayout"; - - private ColorStateList mPrimaryColor; - - private boolean mBackgroundPatterned = true; - - /** - * The color of the background. If null, the color will inherit from mPrimaryColor. - */ - @Nullable - private ColorStateList mBackgroundBaseColor; - - private boolean mLayoutFullscreen = true; - - public GlifLayout(Context context) { - this(context, 0, 0); - } - - public GlifLayout(Context context, int template) { - this(context, template, 0); - } - - public GlifLayout(Context context, int template, int containerId) { - super(context, template, containerId); - init(null, R.attr.suwLayoutTheme); - } + private static final String TAG = "GlifLayout"; - public GlifLayout(Context context, AttributeSet attrs) { - super(context, attrs); - init(attrs, R.attr.suwLayoutTheme); - } + private ColorStateList primaryColor; - @TargetApi(VERSION_CODES.HONEYCOMB) - public GlifLayout(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(attrs, defStyleAttr); - } + private boolean backgroundPatterned = true; - // All the constructors delegate to this init method. The 3-argument constructor is not - // available in LinearLayout before v11, so call super with the exact same arguments. - private void init(AttributeSet attrs, int defStyleAttr) { - registerMixin(HeaderMixin.class, new ColoredHeaderMixin(this, attrs, defStyleAttr)); - registerMixin(IconMixin.class, new IconMixin(this, attrs, defStyleAttr)); - registerMixin(ProgressBarMixin.class, new ProgressBarMixin(this)); - registerMixin(ButtonFooterMixin.class, new ButtonFooterMixin(this)); - final RequireScrollMixin requireScrollMixin = new RequireScrollMixin(this); - registerMixin(RequireScrollMixin.class, requireScrollMixin); - - final ScrollView scrollView = getScrollView(); - if (scrollView != null) { - requireScrollMixin.setScrollHandlingDelegate( - new ScrollViewScrollHandlingDelegate(requireScrollMixin, scrollView)); - } - - TypedArray a = getContext().obtainStyledAttributes(attrs, - R.styleable.SuwGlifLayout, defStyleAttr, 0); - - ColorStateList primaryColor = - a.getColorStateList(R.styleable.SuwGlifLayout_suwColorPrimary); - if (primaryColor != null) { - setPrimaryColor(primaryColor); - } - - ColorStateList backgroundColor = - a.getColorStateList(R.styleable.SuwGlifLayout_suwBackgroundBaseColor); - setBackgroundBaseColor(backgroundColor); - - boolean backgroundPatterned = - a.getBoolean(R.styleable.SuwGlifLayout_suwBackgroundPatterned, true); - setBackgroundPatterned(backgroundPatterned); - - final int footer = a.getResourceId(R.styleable.SuwGlifLayout_suwFooter, 0); - if (footer != 0) { - inflateFooter(footer); - } - - final int stickyHeader = a.getResourceId(R.styleable.SuwGlifLayout_suwStickyHeader, 0); - if (stickyHeader != 0) { - inflateStickyHeader(stickyHeader); - } - - mLayoutFullscreen = a.getBoolean(R.styleable.SuwGlifLayout_suwLayoutFullscreen, true); - - a.recycle(); - - if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && mLayoutFullscreen) { - setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); - } - } + /** The color of the background. If null, the color will inherit from primaryColor. */ + @Nullable private ColorStateList backgroundBaseColor; - @Override - protected View onInflateTemplate(LayoutInflater inflater, @LayoutRes int template) { - if (template == 0) { - template = R.layout.suw_glif_template; - } - return inflateTemplate(inflater, R.style.SuwThemeGlif_Light, template); - } + private boolean layoutFullscreen = true; - @Override - protected ViewGroup findContainer(int containerId) { - if (containerId == 0) { - containerId = R.id.suw_layout_content; - } - return super.findContainer(containerId); - } + public GlifLayout(Context context) { + this(context, 0, 0); + } - /** - * Sets the footer of the layout, which is at the bottom of the content area outside the - * scrolling container. The footer can only be inflated once per instance of this layout. - * - * @param footer The layout to be inflated as footer. - * @return The root of the inflated footer view. - */ - public View inflateFooter(@LayoutRes int footer) { - ViewStub footerStub = findManagedViewById(R.id.suw_layout_footer); - footerStub.setLayoutResource(footer); - return footerStub.inflate(); - } + public GlifLayout(Context context, int template) { + this(context, template, 0); + } - /** - * Sets the sticky header (i.e. header that doesn't scroll) of the layout, which is at the top - * of the content area outside of the scrolling container. The header can only be inflated once - * per instance of this layout. - * - * @param header The layout to be inflated as the header. - * @return The root of the inflated header view. - */ - public View inflateStickyHeader(@LayoutRes int header) { - ViewStub stickyHeaderStub = findManagedViewById(R.id.suw_layout_sticky_header); - stickyHeaderStub.setLayoutResource(header); - return stickyHeaderStub.inflate(); - } + public GlifLayout(Context context, int template, int containerId) { + super(context, template, containerId); + init(null, R.attr.suwLayoutTheme); + } - public ScrollView getScrollView() { - final View view = findManagedViewById(R.id.suw_scroll_view); - return view instanceof ScrollView ? (ScrollView) view : null; - } + public GlifLayout(Context context, AttributeSet attrs) { + super(context, attrs); + init(attrs, R.attr.suwLayoutTheme); + } - public TextView getHeaderTextView() { - return getMixin(HeaderMixin.class).getTextView(); - } + @TargetApi(VERSION_CODES.HONEYCOMB) + public GlifLayout(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(attrs, defStyleAttr); + } - public void setHeaderText(int title) { - getMixin(HeaderMixin.class).setText(title); - } + // All the constructors delegate to this init method. The 3-argument constructor is not + // available in LinearLayout before v11, so call super with the exact same arguments. + private void init(AttributeSet attrs, int defStyleAttr) { + registerMixin(HeaderMixin.class, new ColoredHeaderMixin(this, attrs, defStyleAttr)); + registerMixin(IconMixin.class, new IconMixin(this, attrs, defStyleAttr)); + registerMixin(ProgressBarMixin.class, new ProgressBarMixin(this)); + registerMixin(ButtonFooterMixin.class, new ButtonFooterMixin(this)); + final RequireScrollMixin requireScrollMixin = new RequireScrollMixin(this); + registerMixin(RequireScrollMixin.class, requireScrollMixin); - public void setHeaderText(CharSequence title) { - getMixin(HeaderMixin.class).setText(title); + final ScrollView scrollView = getScrollView(); + if (scrollView != null) { + requireScrollMixin.setScrollHandlingDelegate( + new ScrollViewScrollHandlingDelegate(requireScrollMixin, scrollView)); } - public CharSequence getHeaderText() { - return getMixin(HeaderMixin.class).getText(); - } + TypedArray a = + getContext().obtainStyledAttributes(attrs, R.styleable.SuwGlifLayout, defStyleAttr, 0); - public void setHeaderColor(ColorStateList color) { - final ColoredHeaderMixin mixin = (ColoredHeaderMixin) getMixin(HeaderMixin.class); - mixin.setColor(color); + ColorStateList primaryColor = a.getColorStateList(R.styleable.SuwGlifLayout_suwColorPrimary); + if (primaryColor != null) { + setPrimaryColor(primaryColor); } - public ColorStateList getHeaderColor() { - final ColoredHeaderMixin mixin = (ColoredHeaderMixin) getMixin(HeaderMixin.class); - return mixin.getColor(); - } + ColorStateList backgroundColor = + a.getColorStateList(R.styleable.SuwGlifLayout_suwBackgroundBaseColor); + setBackgroundBaseColor(backgroundColor); - public void setIcon(Drawable icon) { - getMixin(IconMixin.class).setIcon(icon); - } + boolean backgroundPatterned = + a.getBoolean(R.styleable.SuwGlifLayout_suwBackgroundPatterned, true); + setBackgroundPatterned(backgroundPatterned); - public Drawable getIcon() { - return getMixin(IconMixin.class).getIcon(); + final int footer = a.getResourceId(R.styleable.SuwGlifLayout_suwFooter, 0); + if (footer != 0) { + inflateFooter(footer); } - /** - * Sets the primary color of this layout, which will be used to determine the color of the - * progress bar and the background pattern. - */ - public void setPrimaryColor(@NonNull ColorStateList color) { - mPrimaryColor = color; - updateBackground(); - getMixin(ProgressBarMixin.class).setColor(color); + final int stickyHeader = a.getResourceId(R.styleable.SuwGlifLayout_suwStickyHeader, 0); + if (stickyHeader != 0) { + inflateStickyHeader(stickyHeader); } - public ColorStateList getPrimaryColor() { - return mPrimaryColor; - } + layoutFullscreen = a.getBoolean(R.styleable.SuwGlifLayout_suwLayoutFullscreen, true); - /** - * Sets the base color of the background view, which is the status bar for phones and the full- - * screen background for tablets. If {@link #isBackgroundPatterned()} is true, the pattern will - * be drawn with this color. - * - * @param color The color to use as the base color of the background. If {@code null}, - * {@link #getPrimaryColor()} will be used. - */ - public void setBackgroundBaseColor(@Nullable ColorStateList color) { - mBackgroundBaseColor = color; - updateBackground(); - } + a.recycle(); - /** - * @return The base color of the background. {@code null} indicates the background will be drawn - * with {@link #getPrimaryColor()}. - */ - @Nullable - public ColorStateList getBackgroundBaseColor() { - return mBackgroundBaseColor; + if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && layoutFullscreen) { + setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } + } - /** - * Sets whether the background should be {@link GlifPatternDrawable}. If {@code false}, the - * background will be a solid color. - */ - public void setBackgroundPatterned(boolean patterned) { - mBackgroundPatterned = patterned; - updateBackground(); + @Override + protected View onInflateTemplate(LayoutInflater inflater, @LayoutRes int template) { + if (template == 0) { + template = R.layout.suw_glif_template; } + return inflateTemplate(inflater, R.style.SuwThemeGlif_Light, template); + } - /** - * @return True if this view uses {@link GlifPatternDrawable} as background. - */ - public boolean isBackgroundPatterned() { - return mBackgroundPatterned; + @Override + protected ViewGroup findContainer(int containerId) { + if (containerId == 0) { + containerId = R.id.suw_layout_content; } - - private void updateBackground() { - final View patternBg = findManagedViewById(R.id.suw_pattern_bg); - if (patternBg != null) { - int backgroundColor = 0; - if (mBackgroundBaseColor != null) { - backgroundColor = mBackgroundBaseColor.getDefaultColor(); - } else if (mPrimaryColor != null) { - backgroundColor = mPrimaryColor.getDefaultColor(); - } - Drawable background = mBackgroundPatterned - ? new GlifPatternDrawable(backgroundColor) - : new ColorDrawable(backgroundColor); - if (patternBg instanceof StatusBarBackgroundLayout) { - ((StatusBarBackgroundLayout) patternBg).setStatusBarBackground(background); - } else { - patternBg.setBackgroundDrawable(background); - } - } + return super.findContainer(containerId); + } + + /** + * Sets the footer of the layout, which is at the bottom of the content area outside the scrolling + * container. The footer can only be inflated once per instance of this layout. + * + * @param footer The layout to be inflated as footer. + * @return The root of the inflated footer view. + */ + public View inflateFooter(@LayoutRes int footer) { + ViewStub footerStub = findManagedViewById(R.id.suw_layout_footer); + footerStub.setLayoutResource(footer); + return footerStub.inflate(); + } + + /** + * Sets the sticky header (i.e. header that doesn't scroll) of the layout, which is at the top of + * the content area outside of the scrolling container. The header can only be inflated once per + * instance of this layout. + * + * @param header The layout to be inflated as the header. + * @return The root of the inflated header view. + */ + public View inflateStickyHeader(@LayoutRes int header) { + ViewStub stickyHeaderStub = findManagedViewById(R.id.suw_layout_sticky_header); + stickyHeaderStub.setLayoutResource(header); + return stickyHeaderStub.inflate(); + } + + public ScrollView getScrollView() { + final View view = findManagedViewById(R.id.suw_scroll_view); + return view instanceof ScrollView ? (ScrollView) view : null; + } + + public TextView getHeaderTextView() { + return getMixin(HeaderMixin.class).getTextView(); + } + + public void setHeaderText(int title) { + getMixin(HeaderMixin.class).setText(title); + } + + public void setHeaderText(CharSequence title) { + getMixin(HeaderMixin.class).setText(title); + } + + public CharSequence getHeaderText() { + return getMixin(HeaderMixin.class).getText(); + } + + public void setHeaderColor(ColorStateList color) { + final ColoredHeaderMixin mixin = (ColoredHeaderMixin) getMixin(HeaderMixin.class); + mixin.setColor(color); + } + + public ColorStateList getHeaderColor() { + final ColoredHeaderMixin mixin = (ColoredHeaderMixin) getMixin(HeaderMixin.class); + return mixin.getColor(); + } + + public void setIcon(Drawable icon) { + getMixin(IconMixin.class).setIcon(icon); + } + + public Drawable getIcon() { + return getMixin(IconMixin.class).getIcon(); + } + + /** + * Sets the primary color of this layout, which will be used to determine the color of the + * progress bar and the background pattern. + */ + public void setPrimaryColor(@NonNull ColorStateList color) { + primaryColor = color; + updateBackground(); + getMixin(ProgressBarMixin.class).setColor(color); + } + + public ColorStateList getPrimaryColor() { + return primaryColor; + } + + /** + * Sets the base color of the background view, which is the status bar for phones and the full- + * screen background for tablets. If {@link #isBackgroundPatterned()} is true, the pattern will be + * drawn with this color. + * + * @param color The color to use as the base color of the background. If {@code null}, {@link + * #getPrimaryColor()} will be used. + */ + public void setBackgroundBaseColor(@Nullable ColorStateList color) { + backgroundBaseColor = color; + updateBackground(); + } + + /** + * @return The base color of the background. {@code null} indicates the background will be drawn + * with {@link #getPrimaryColor()}. + */ + @Nullable + public ColorStateList getBackgroundBaseColor() { + return backgroundBaseColor; + } + + /** + * Sets whether the background should be {@link GlifPatternDrawable}. If {@code false}, the + * background will be a solid color. + */ + public void setBackgroundPatterned(boolean patterned) { + backgroundPatterned = patterned; + updateBackground(); + } + + /** @return True if this view uses {@link GlifPatternDrawable} as background. */ + public boolean isBackgroundPatterned() { + return backgroundPatterned; + } + + private void updateBackground() { + final View patternBg = findManagedViewById(R.id.suw_pattern_bg); + if (patternBg != null) { + int backgroundColor = 0; + if (backgroundBaseColor != null) { + backgroundColor = backgroundBaseColor.getDefaultColor(); + } else if (primaryColor != null) { + backgroundColor = primaryColor.getDefaultColor(); + } + Drawable background = + backgroundPatterned + ? new GlifPatternDrawable(backgroundColor) + : new ColorDrawable(backgroundColor); + if (patternBg instanceof StatusBarBackgroundLayout) { + ((StatusBarBackgroundLayout) patternBg).setStatusBarBackground(background); + } else { + patternBg.setBackgroundDrawable(background); + } } + } - public boolean isProgressBarShown() { - return getMixin(ProgressBarMixin.class).isShown(); - } + public boolean isProgressBarShown() { + return getMixin(ProgressBarMixin.class).isShown(); + } - public void setProgressBarShown(boolean shown) { - getMixin(ProgressBarMixin.class).setShown(shown); - } + public void setProgressBarShown(boolean shown) { + getMixin(ProgressBarMixin.class).setShown(shown); + } - public ProgressBar peekProgressBar() { - return getMixin(ProgressBarMixin.class).peekProgressBar(); - } + public ProgressBar peekProgressBar() { + return getMixin(ProgressBarMixin.class).peekProgressBar(); + } } diff --git a/library/main/src/com/android/setupwizardlib/GlifListLayout.java b/library/main/src/com/android/setupwizardlib/GlifListLayout.java index 8266e5f..c4f66fa 100644 --- a/library/main/src/com/android/setupwizardlib/GlifListLayout.java +++ b/library/main/src/com/android/setupwizardlib/GlifListLayout.java @@ -26,7 +26,6 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; - import com.android.setupwizardlib.template.ListMixin; import com.android.setupwizardlib.template.ListViewScrollHandlingDelegate; import com.android.setupwizardlib.template.RequireScrollMixin; @@ -37,130 +36,113 @@ import com.android.setupwizardlib.template.RequireScrollMixin; */ public class GlifListLayout extends GlifLayout { - /* static section */ - - private static final String TAG = "GlifListLayout"; - - /* non-static section */ - - private ListMixin mListMixin; - - public GlifListLayout(Context context) { - this(context, 0, 0); - } - - public GlifListLayout(Context context, int template) { - this(context, template, 0); - } - - public GlifListLayout(Context context, int template, int containerId) { - super(context, template, containerId); - init(context, null, 0); - } - - public GlifListLayout(Context context, AttributeSet attrs) { - super(context, attrs); - init(context, attrs, 0); - } - - @TargetApi(VERSION_CODES.HONEYCOMB) - public GlifListLayout(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(context, attrs, defStyleAttr); - } - - private void init(Context context, AttributeSet attrs, int defStyleAttr) { - mListMixin = new ListMixin(this, attrs, defStyleAttr); - registerMixin(ListMixin.class, mListMixin); - - final RequireScrollMixin requireScrollMixin = getMixin(RequireScrollMixin.class); - requireScrollMixin.setScrollHandlingDelegate( - new ListViewScrollHandlingDelegate(requireScrollMixin, getListView())); - } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - super.onLayout(changed, left, top, right, bottom); - mListMixin.onLayout(); - } - - @Override - protected View onInflateTemplate(LayoutInflater inflater, int template) { - if (template == 0) { - template = R.layout.suw_glif_list_template; - } - return super.onInflateTemplate(inflater, template); - } - - @Override - protected ViewGroup findContainer(int containerId) { - if (containerId == 0) { - containerId = android.R.id.list; - } - return super.findContainer(containerId); - } - - public ListView getListView() { - return mListMixin.getListView(); - } - - public void setAdapter(ListAdapter adapter) { - mListMixin.setAdapter(adapter); - } - - public ListAdapter getAdapter() { - return mListMixin.getAdapter(); - } - - /** - * @deprecated Use {@link #setDividerInsets(int, int)} instead. - */ - @Deprecated - public void setDividerInset(int inset) { - mListMixin.setDividerInset(inset); - } - - /** - * Sets the start inset of the divider. This will use the default divider drawable set in the - * theme and apply insets to it. - * - * @param start The number of pixels to inset on the "start" side of the list divider. Typically - * this will be either {@code @dimen/suw_items_glif_icon_divider_inset} or - * {@code @dimen/suw_items_glif_text_divider_inset}. - * @param end The number of pixels to inset on the "end" side of the list divider. - * - * @see ListMixin#setDividerInsets(int, int) - */ - public void setDividerInsets(int start, int end) { - mListMixin.setDividerInsets(start, end); - } - - /** - * @deprecated Use {@link #getDividerInsetStart()} instead. - */ - @Deprecated - public int getDividerInset() { - return mListMixin.getDividerInset(); - } - - /** - * @see ListMixin#getDividerInsetStart() - */ - public int getDividerInsetStart() { - return mListMixin.getDividerInsetStart(); - } - - /** - * @see ListMixin#getDividerInsetEnd() - */ - public int getDividerInsetEnd() { - return mListMixin.getDividerInsetEnd(); - } - - /** - * @see ListMixin#getDivider() - */ - public Drawable getDivider() { - return mListMixin.getDivider(); - } + private ListMixin listMixin; + + public GlifListLayout(Context context) { + this(context, 0, 0); + } + + public GlifListLayout(Context context, int template) { + this(context, template, 0); + } + + public GlifListLayout(Context context, int template, int containerId) { + super(context, template, containerId); + init(null, 0); + } + + public GlifListLayout(Context context, AttributeSet attrs) { + super(context, attrs); + init(attrs, 0); + } + + @TargetApi(VERSION_CODES.HONEYCOMB) + public GlifListLayout(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(attrs, defStyleAttr); + } + + private void init(AttributeSet attrs, int defStyleAttr) { + listMixin = new ListMixin(this, attrs, defStyleAttr); + registerMixin(ListMixin.class, listMixin); + + final RequireScrollMixin requireScrollMixin = getMixin(RequireScrollMixin.class); + requireScrollMixin.setScrollHandlingDelegate( + new ListViewScrollHandlingDelegate(requireScrollMixin, getListView())); + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + super.onLayout(changed, left, top, right, bottom); + listMixin.onLayout(); + } + + @Override + protected View onInflateTemplate(LayoutInflater inflater, int template) { + if (template == 0) { + template = R.layout.suw_glif_list_template; + } + return super.onInflateTemplate(inflater, template); + } + + @Override + protected ViewGroup findContainer(int containerId) { + if (containerId == 0) { + containerId = android.R.id.list; + } + return super.findContainer(containerId); + } + + public ListView getListView() { + return listMixin.getListView(); + } + + public void setAdapter(ListAdapter adapter) { + listMixin.setAdapter(adapter); + } + + public ListAdapter getAdapter() { + return listMixin.getAdapter(); + } + + /** @deprecated Use {@link #setDividerInsets(int, int)} instead. */ + @Deprecated + public void setDividerInset(int inset) { + listMixin.setDividerInset(inset); + } + + /** + * Sets the start inset of the divider. This will use the default divider drawable set in the + * theme and apply insets to it. + * + * @param start The number of pixels to inset on the "start" side of the list divider. Typically + * this will be either {@code @dimen/suw_items_glif_icon_divider_inset} or + * {@code @dimen/suw_items_glif_text_divider_inset}. + * @param end The number of pixels to inset on the "end" side of the list divider. + * @see ListMixin#setDividerInsets(int, int) + */ + public void setDividerInsets(int start, int end) { + listMixin.setDividerInsets(start, end); + } + + /** @deprecated Use {@link #getDividerInsetStart()} instead. */ + @Deprecated + public int getDividerInset() { + return listMixin.getDividerInset(); + } + + /** @see ListMixin#getDividerInsetStart() */ + public int getDividerInsetStart() { + return listMixin.getDividerInsetStart(); + } + + /** @see ListMixin#getDividerInsetEnd() */ + public int getDividerInsetEnd() { + return listMixin.getDividerInsetEnd(); + } + + /** @see ListMixin#getDivider() */ + public Drawable getDivider() { + return listMixin.getDivider(); + } } diff --git a/library/main/src/com/android/setupwizardlib/GlifPatternDrawable.java b/library/main/src/com/android/setupwizardlib/GlifPatternDrawable.java index caf92ac..f65f3ec 100644 --- a/library/main/src/com/android/setupwizardlib/GlifPatternDrawable.java +++ b/library/main/src/com/android/setupwizardlib/GlifPatternDrawable.java @@ -31,10 +31,8 @@ import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; - import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; - import java.lang.ref.SoftReference; /** @@ -42,263 +40,258 @@ import java.lang.ref.SoftReference; * tablets in GLIF layout. */ public class GlifPatternDrawable extends Drawable { - /* - * This class essentially implements a simple SVG in Java code, with some special handling of - * scaling when given different bounds. - */ - - /* static section */ - - @SuppressLint("InlinedApi") - private static final int[] ATTRS_PRIMARY_COLOR = new int[]{ android.R.attr.colorPrimary }; - - private static final float VIEWBOX_HEIGHT = 768f; - private static final float VIEWBOX_WIDTH = 1366f; - // X coordinate of scale focus, as a fraction of of the width. (Range is 0 - 1) - private static final float SCALE_FOCUS_X = .146f; - // Y coordinate of scale focus, as a fraction of of the height. (Range is 0 - 1) - private static final float SCALE_FOCUS_Y = .228f; - - // Alpha component of the color to be drawn, on top of the grayscale pattern. (Range is 0 - 1) - private static final float COLOR_ALPHA = .8f; - // Int version of COLOR_ALPHA. (Range is 0 - 255) - private static final int COLOR_ALPHA_INT = (int) (COLOR_ALPHA * 255); - - // Cap the bitmap size, such that it won't hurt the performance too much - // and it won't crash due to a very large scale. - // The drawable will look blurry above this size. - // This is a multiplier applied on top of the viewbox size. - // Resulting max cache size = (1.5 x 1366, 1.5 x 768) = (2049, 1152) - private static final float MAX_CACHED_BITMAP_SCALE = 1.5f; - - private static final int NUM_PATHS = 7; - - private static SoftReference<Bitmap> sBitmapCache; - private static Path[] sPatternPaths; - private static int[] sPatternLightness; - - public static GlifPatternDrawable getDefault(Context context) { - int colorPrimary = 0; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - final TypedArray a = context.obtainStyledAttributes(ATTRS_PRIMARY_COLOR); - colorPrimary = a.getColor(0, Color.BLACK); - a.recycle(); - } - return new GlifPatternDrawable(colorPrimary); - } - - @VisibleForTesting - public static void invalidatePattern() { - sBitmapCache = null; - } - - /* non-static section */ - - private int mColor; - private Paint mTempPaint = new Paint(Paint.ANTI_ALIAS_FLAG); - - public GlifPatternDrawable(int color) { - setColor(color); + /* + * This class essentially implements a simple SVG in Java code, with some special handling of + * scaling when given different bounds. + */ + + /* static section */ + + @SuppressLint("InlinedApi") + private static final int[] ATTRS_PRIMARY_COLOR = new int[] {android.R.attr.colorPrimary}; + + private static final float VIEWBOX_HEIGHT = 768f; + private static final float VIEWBOX_WIDTH = 1366f; + // X coordinate of scale focus, as a fraction of the width. (Range is 0 - 1) + private static final float SCALE_FOCUS_X = .146f; + // Y coordinate of scale focus, as a fraction of the height. (Range is 0 - 1) + private static final float SCALE_FOCUS_Y = .228f; + + // Alpha component of the color to be drawn, on top of the grayscale pattern. (Range is 0 - 1) + private static final float COLOR_ALPHA = .8f; + // Int version of COLOR_ALPHA. (Range is 0 - 255) + private static final int COLOR_ALPHA_INT = (int) (COLOR_ALPHA * 255); + + // Cap the bitmap size, such that it won't hurt the performance too much + // and it won't crash due to a very large scale. + // The drawable will look blurry above this size. + // This is a multiplier applied on top of the viewbox size. + // Resulting max cache size = (1.5 x 1366, 1.5 x 768) = (2049, 1152) + private static final float MAX_CACHED_BITMAP_SCALE = 1.5f; + + private static final int NUM_PATHS = 7; + + private static SoftReference<Bitmap> bitmapCache; + private static Path[] patternPaths; + private static int[] patternLightness; + + public static GlifPatternDrawable getDefault(Context context) { + int colorPrimary = 0; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + final TypedArray a = context.obtainStyledAttributes(ATTRS_PRIMARY_COLOR); + colorPrimary = a.getColor(0, Color.BLACK); + a.recycle(); } - - @Override - public void draw(@NonNull Canvas canvas) { - final Rect bounds = getBounds(); - int drawableWidth = bounds.width(); - int drawableHeight = bounds.height(); - Bitmap bitmap = null; - if (sBitmapCache != null) { - bitmap = sBitmapCache.get(); - } - if (bitmap != null) { - final int bitmapWidth = bitmap.getWidth(); - final int bitmapHeight = bitmap.getHeight(); - // Invalidate the cache if this drawable is bigger and we can still create a bigger - // cache. - if (drawableWidth > bitmapWidth - && bitmapWidth < VIEWBOX_WIDTH * MAX_CACHED_BITMAP_SCALE) { - bitmap = null; - } else if (drawableHeight > bitmapHeight - && bitmapHeight < VIEWBOX_HEIGHT * MAX_CACHED_BITMAP_SCALE) { - bitmap = null; - } - } - - if (bitmap == null) { - // Reset the paint so it can be used to draw the paths in renderOnCanvas - mTempPaint.reset(); - - bitmap = createBitmapCache(drawableWidth, drawableHeight); - sBitmapCache = new SoftReference<>(bitmap); - - // Reset the paint to so it can be used to draw the bitmap - mTempPaint.reset(); - } - - canvas.save(); - canvas.clipRect(bounds); - - scaleCanvasToBounds(canvas, bitmap, bounds); - canvas.drawColor(Color.BLACK); - mTempPaint.setColor(Color.WHITE); - canvas.drawBitmap(bitmap, 0, 0, mTempPaint); - canvas.drawColor(mColor); - - canvas.restore(); + return new GlifPatternDrawable(colorPrimary); + } + + @VisibleForTesting + public static void invalidatePattern() { + bitmapCache = null; + } + + /* non-static section */ + + private int color; + private final Paint tempPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + + public GlifPatternDrawable(int color) { + setColor(color); + } + + @Override + public void draw(@NonNull Canvas canvas) { + final Rect bounds = getBounds(); + int drawableWidth = bounds.width(); + int drawableHeight = bounds.height(); + Bitmap bitmap = null; + if (bitmapCache != null) { + bitmap = bitmapCache.get(); } - - @VisibleForTesting - public Bitmap createBitmapCache(int drawableWidth, int drawableHeight) { - float scaleX = drawableWidth / VIEWBOX_WIDTH; - float scaleY = drawableHeight / VIEWBOX_HEIGHT; - float scale = Math.max(scaleX, scaleY); - scale = Math.min(MAX_CACHED_BITMAP_SCALE, scale); - - - int scaledWidth = (int) (VIEWBOX_WIDTH * scale); - int scaledHeight = (int) (VIEWBOX_HEIGHT * scale); - - // Use ALPHA_8 mask to save memory, since the pattern is grayscale only anyway. - Bitmap bitmap = Bitmap.createBitmap( - scaledWidth, - scaledHeight, - Bitmap.Config.ALPHA_8); - Canvas bitmapCanvas = new Canvas(bitmap); - renderOnCanvas(bitmapCanvas, scale); - return bitmap; + if (bitmap != null) { + final int bitmapWidth = bitmap.getWidth(); + final int bitmapHeight = bitmap.getHeight(); + // Invalidate the cache if this drawable is bigger and we can still create a bigger + // cache. + if (drawableWidth > bitmapWidth && bitmapWidth < VIEWBOX_WIDTH * MAX_CACHED_BITMAP_SCALE) { + bitmap = null; + } else if (drawableHeight > bitmapHeight + && bitmapHeight < VIEWBOX_HEIGHT * MAX_CACHED_BITMAP_SCALE) { + bitmap = null; + } } - private void renderOnCanvas(Canvas canvas, float scale) { - canvas.save(); - canvas.scale(scale, scale); - - mTempPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); - - // Draw the pattern by creating the paths, adjusting the colors and drawing them. The path - // values are extracted from the SVG of the pattern file. - - if (sPatternPaths == null) { - sPatternPaths = new Path[NUM_PATHS]; - // Lightness values of the pattern, range 0 - 255 - sPatternLightness = new int[] { 10, 40, 51, 66, 91, 112, 130 }; - - Path p = sPatternPaths[0] = new Path(); - p.moveTo(1029.4f, 357.5f); - p.lineTo(1366f, 759.1f); - p.lineTo(1366f, 0f); - p.lineTo(1137.7f, 0f); - p.close(); - - p = sPatternPaths[1] = new Path(); - p.moveTo(1138.1f, 0f); - p.rLineTo(-144.8f, 768f); - p.rLineTo(372.7f, 0f); - p.rLineTo(0f, -524f); - p.cubicTo(1290.7f, 121.6f, 1219.2f, 41.1f, 1178.7f, 0f); - p.close(); - - p = sPatternPaths[2] = new Path(); - p.moveTo(949.8f, 768f); - p.rCubicTo(92.6f, -170.6f, 213f, -440.3f, 269.4f, -768f); - p.lineTo(585f, 0f); - p.rLineTo(2.1f, 766f); - p.close(); - - p = sPatternPaths[3] = new Path(); - p.moveTo(471.1f, 768f); - p.rMoveTo(704.5f, 0f); - p.cubicTo(1123.6f, 563.3f, 1027.4f, 275.2f, 856.2f, 0f); - p.lineTo(476.4f, 0f); - p.rLineTo(-5.3f, 768f); - p.close(); - - p = sPatternPaths[4] = new Path(); - p.moveTo(323.1f, 768f); - p.moveTo(777.5f, 768f); - p.cubicTo(661.9f, 348.8f, 427.2f, 21.4f, 401.2f, 25.4f); - p.lineTo(323.1f, 768f); - p.close(); - - p = sPatternPaths[5] = new Path(); - p.moveTo(178.44286f, 766.8571f); - p.lineTo(308.7f, 768f); - p.cubicTo(381.7f, 604.6f, 481.6f, 344.3f, 562.2f, 0f); - p.lineTo(0f, 0f); - p.close(); - - p = sPatternPaths[6] = new Path(); - p.moveTo(146f, 0f); - p.lineTo(0f, 0f); - p.lineTo(0f, 768f); - p.lineTo(394.2f, 768f); - p.cubicTo(327.7f, 475.3f, 228.5f, 201f, 146f, 0f); - p.close(); - } - - for (int i = 0; i < NUM_PATHS; i++) { - // Color is 0xAARRGGBB, so alpha << 24 will create a color with (alpha)% black. - // Although the color components don't really matter, since the backing bitmap cache is - // ALPHA_8. - mTempPaint.setColor(sPatternLightness[i] << 24); - canvas.drawPath(sPatternPaths[i], mTempPaint); - } - - canvas.restore(); - mTempPaint.reset(); - } + if (bitmap == null) { + // Reset the paint so it can be used to draw the paths in renderOnCanvas + tempPaint.reset(); - @VisibleForTesting - public void scaleCanvasToBounds(Canvas canvas, Bitmap bitmap, Rect drawableBounds) { - int bitmapWidth = bitmap.getWidth(); - int bitmapHeight = bitmap.getHeight(); - float scaleX = drawableBounds.width() / (float) bitmapWidth; - float scaleY = drawableBounds.height() / (float) bitmapHeight; - - // First scale both sides to fit independently. - canvas.scale(scaleX, scaleY); - if (scaleY > scaleX) { - // Adjust x-scale to maintain aspect ratio using the pivot, so that more of the texture - // and less of the blank space on the left edge is seen. - canvas.scale(scaleY / scaleX, 1f, SCALE_FOCUS_X * bitmapWidth, 0f); - } else if (scaleX > scaleY) { - // Adjust y-scale to maintain aspect ratio using the pivot, so that an intersection of - // two "circles" can always be seen. - canvas.scale(1f, scaleX / scaleY, 0f, SCALE_FOCUS_Y * bitmapHeight); - } - } - - @Override - public void setAlpha(int i) { - // Ignore - } + bitmap = createBitmapCache(drawableWidth, drawableHeight); + bitmapCache = new SoftReference<>(bitmap); - @Override - public void setColorFilter(ColorFilter colorFilter) { - // Ignore + // Reset the paint to so it can be used to draw the bitmap + tempPaint.reset(); } - @Override - public int getOpacity() { - return PixelFormat.UNKNOWN; + canvas.save(); + canvas.clipRect(bounds); + + scaleCanvasToBounds(canvas, bitmap, bounds); + canvas.drawColor(Color.BLACK); + tempPaint.setColor(Color.WHITE); + canvas.drawBitmap(bitmap, 0, 0, tempPaint); + canvas.drawColor(color); + + canvas.restore(); + } + + @VisibleForTesting + public Bitmap createBitmapCache(int drawableWidth, int drawableHeight) { + float scaleX = drawableWidth / VIEWBOX_WIDTH; + float scaleY = drawableHeight / VIEWBOX_HEIGHT; + float scale = Math.max(scaleX, scaleY); + scale = Math.min(MAX_CACHED_BITMAP_SCALE, scale); + + int scaledWidth = (int) (VIEWBOX_WIDTH * scale); + int scaledHeight = (int) (VIEWBOX_HEIGHT * scale); + + // Use ALPHA_8 mask to save memory, since the pattern is grayscale only anyway. + Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ALPHA_8); + Canvas bitmapCanvas = new Canvas(bitmap); + renderOnCanvas(bitmapCanvas, scale); + return bitmap; + } + + private void renderOnCanvas(Canvas canvas, float scale) { + canvas.save(); + canvas.scale(scale, scale); + + tempPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); + + // Draw the pattern by creating the paths, adjusting the colors and drawing them. The path + // values are extracted from the SVG of the pattern file. + + if (patternPaths == null) { + patternPaths = new Path[NUM_PATHS]; + // Lightness values of the pattern, range 0 - 255 + patternLightness = new int[] {10, 40, 51, 66, 91, 112, 130}; + + Path p = patternPaths[0] = new Path(); + p.moveTo(1029.4f, 357.5f); + p.lineTo(1366f, 759.1f); + p.lineTo(1366f, 0f); + p.lineTo(1137.7f, 0f); + p.close(); + + p = patternPaths[1] = new Path(); + p.moveTo(1138.1f, 0f); + p.rLineTo(-144.8f, 768f); + p.rLineTo(372.7f, 0f); + p.rLineTo(0f, -524f); + p.cubicTo(1290.7f, 121.6f, 1219.2f, 41.1f, 1178.7f, 0f); + p.close(); + + p = patternPaths[2] = new Path(); + p.moveTo(949.8f, 768f); + p.rCubicTo(92.6f, -170.6f, 213f, -440.3f, 269.4f, -768f); + p.lineTo(585f, 0f); + p.rLineTo(2.1f, 766f); + p.close(); + + p = patternPaths[3] = new Path(); + p.moveTo(471.1f, 768f); + p.rMoveTo(704.5f, 0f); + p.cubicTo(1123.6f, 563.3f, 1027.4f, 275.2f, 856.2f, 0f); + p.lineTo(476.4f, 0f); + p.rLineTo(-5.3f, 768f); + p.close(); + + p = patternPaths[4] = new Path(); + p.moveTo(323.1f, 768f); + p.moveTo(777.5f, 768f); + p.cubicTo(661.9f, 348.8f, 427.2f, 21.4f, 401.2f, 25.4f); + p.lineTo(323.1f, 768f); + p.close(); + + p = patternPaths[5] = new Path(); + p.moveTo(178.44286f, 766.8571f); + p.lineTo(308.7f, 768f); + p.cubicTo(381.7f, 604.6f, 481.6f, 344.3f, 562.2f, 0f); + p.lineTo(0f, 0f); + p.close(); + + p = patternPaths[6] = new Path(); + p.moveTo(146f, 0f); + p.lineTo(0f, 0f); + p.lineTo(0f, 768f); + p.lineTo(394.2f, 768f); + p.cubicTo(327.7f, 475.3f, 228.5f, 201f, 146f, 0f); + p.close(); } - /** - * Sets the color used as the base color of this pattern drawable. The alpha component of the - * color will be ignored. - */ - public void setColor(int color) { - final int r = Color.red(color); - final int g = Color.green(color); - final int b = Color.blue(color); - mColor = Color.argb(COLOR_ALPHA_INT, r, g, b); - invalidateSelf(); + for (int i = 0; i < NUM_PATHS; i++) { + // Color is 0xAARRGGBB, so alpha << 24 will create a color with (alpha)% black. + // Although the color components don't really matter, since the backing bitmap cache is + // ALPHA_8. + tempPaint.setColor(patternLightness[i] << 24); + canvas.drawPath(patternPaths[i], tempPaint); } - /** - * @return The color used as the base color of this pattern drawable. The alpha component of - * this is always 255. - */ - public int getColor() { - return Color.argb(255, Color.red(mColor), Color.green(mColor), Color.blue(mColor)); + canvas.restore(); + tempPaint.reset(); + } + + @VisibleForTesting + public void scaleCanvasToBounds(Canvas canvas, Bitmap bitmap, Rect drawableBounds) { + int bitmapWidth = bitmap.getWidth(); + int bitmapHeight = bitmap.getHeight(); + float scaleX = drawableBounds.width() / (float) bitmapWidth; + float scaleY = drawableBounds.height() / (float) bitmapHeight; + + // First scale both sides to fit independently. + canvas.scale(scaleX, scaleY); + if (scaleY > scaleX) { + // Adjust x-scale to maintain aspect ratio using the pivot, so that more of the texture + // and less of the blank space on the left edge is seen. + canvas.scale(scaleY / scaleX, 1f, SCALE_FOCUS_X * bitmapWidth, 0f); + } else if (scaleX > scaleY) { + // Adjust y-scale to maintain aspect ratio using the pivot, so that an intersection of + // two "circles" can always be seen. + canvas.scale(1f, scaleX / scaleY, 0f, SCALE_FOCUS_Y * bitmapHeight); } + } + + @Override + public void setAlpha(int i) { + // Ignore + } + + @Override + public void setColorFilter(ColorFilter colorFilter) { + // Ignore + } + + @Override + public int getOpacity() { + return PixelFormat.UNKNOWN; + } + + /** + * Sets the color used as the base color of this pattern drawable. The alpha component of the + * color will be ignored. + */ + public void setColor(int color) { + final int r = Color.red(color); + final int g = Color.green(color); + final int b = Color.blue(color); + this.color = Color.argb(COLOR_ALPHA_INT, r, g, b); + invalidateSelf(); + } + + /** + * @return The color used as the base color of this pattern drawable. The alpha component of this + * is always 255. + */ + public int getColor() { + return Color.argb(255, Color.red(color), Color.green(color), Color.blue(color)); + } } diff --git a/library/main/src/com/android/setupwizardlib/SetupWizardItemsLayout.java b/library/main/src/com/android/setupwizardlib/SetupWizardItemsLayout.java index d520873..6197c4c 100644 --- a/library/main/src/com/android/setupwizardlib/SetupWizardItemsLayout.java +++ b/library/main/src/com/android/setupwizardlib/SetupWizardItemsLayout.java @@ -17,34 +17,30 @@ package com.android.setupwizardlib; import android.content.Context; +import androidx.annotation.Nullable; import android.util.AttributeSet; import android.widget.ListAdapter; - -import androidx.annotation.Nullable; - import com.android.setupwizardlib.items.ItemAdapter; -/** - * @deprecated Use {@link SetupWizardListLayout} instead. - */ +/** @deprecated Use {@link SetupWizardListLayout} instead. */ @Deprecated public class SetupWizardItemsLayout extends SetupWizardListLayout { - public SetupWizardItemsLayout(Context context, AttributeSet attrs) { - super(context, attrs); - } + public SetupWizardItemsLayout(Context context, AttributeSet attrs) { + super(context, attrs); + } - public SetupWizardItemsLayout(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } + public SetupWizardItemsLayout(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } - @Override - @Nullable - public ItemAdapter getAdapter() { - final ListAdapter adapter = super.getAdapter(); - if (adapter instanceof ItemAdapter) { - return (ItemAdapter) adapter; - } - return null; + @Override + @Nullable + public ItemAdapter getAdapter() { + final ListAdapter adapter = super.getAdapter(); + if (adapter instanceof ItemAdapter) { + return (ItemAdapter) adapter; } + return null; + } } diff --git a/library/main/src/com/android/setupwizardlib/SetupWizardLayout.java b/library/main/src/com/android/setupwizardlib/SetupWizardLayout.java index 065d2ef..792d102 100644 --- a/library/main/src/com/android/setupwizardlib/SetupWizardLayout.java +++ b/library/main/src/com/android/setupwizardlib/SetupWizardLayout.java @@ -38,7 +38,6 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; import android.widget.TextView; - import com.android.setupwizardlib.template.HeaderMixin; import com.android.setupwizardlib.template.NavigationBarMixin; import com.android.setupwizardlib.template.ProgressBarMixin; @@ -49,385 +48,377 @@ import com.android.setupwizardlib.view.NavigationBar; public class SetupWizardLayout extends TemplateLayout { - private static final String TAG = "SetupWizardLayout"; - - public SetupWizardLayout(Context context) { - super(context, 0, 0); - init(null, R.attr.suwLayoutTheme); - } - - public SetupWizardLayout(Context context, int template) { - this(context, template, 0); - } - - public SetupWizardLayout(Context context, int template, int containerId) { - super(context, template, containerId); - init(null, R.attr.suwLayoutTheme); - } - - public SetupWizardLayout(Context context, AttributeSet attrs) { - super(context, attrs); - init(attrs, R.attr.suwLayoutTheme); - } - - @TargetApi(VERSION_CODES.HONEYCOMB) - public SetupWizardLayout(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(attrs, defStyleAttr); - } - - // All the constructors delegate to this init method. The 3-argument constructor is not - // available in LinearLayout before v11, so call super with the exact same arguments. - private void init(AttributeSet attrs, int defStyleAttr) { - registerMixin(HeaderMixin.class, new HeaderMixin(this, attrs, defStyleAttr)); - registerMixin(ProgressBarMixin.class, new ProgressBarMixin(this)); - registerMixin(NavigationBarMixin.class, new NavigationBarMixin(this)); - final RequireScrollMixin requireScrollMixin = new RequireScrollMixin(this); - registerMixin(RequireScrollMixin.class, requireScrollMixin); - - final ScrollView scrollView = getScrollView(); - if (scrollView != null) { - requireScrollMixin.setScrollHandlingDelegate( - new ScrollViewScrollHandlingDelegate(requireScrollMixin, scrollView)); - } - - final TypedArray a = getContext().obtainStyledAttributes(attrs, - R.styleable.SuwSetupWizardLayout, defStyleAttr, 0); - - // Set the background from XML, either directly or built from a bitmap tile - final Drawable background = - a.getDrawable(R.styleable.SuwSetupWizardLayout_suwBackground); - if (background != null) { - setLayoutBackground(background); - } else { - final Drawable backgroundTile = - a.getDrawable(R.styleable.SuwSetupWizardLayout_suwBackgroundTile); - if (backgroundTile != null) { - setBackgroundTile(backgroundTile); - } - } - - // Set the illustration from XML, either directly or built from image + horizontal tile - final Drawable illustration = - a.getDrawable(R.styleable.SuwSetupWizardLayout_suwIllustration); - if (illustration != null) { - setIllustration(illustration); - } else { - final Drawable illustrationImage = - a.getDrawable(R.styleable.SuwSetupWizardLayout_suwIllustrationImage); - final Drawable horizontalTile = a.getDrawable( - R.styleable.SuwSetupWizardLayout_suwIllustrationHorizontalTile); - if (illustrationImage != null && horizontalTile != null) { - setIllustration(illustrationImage, horizontalTile); - } - } - - // Set the top padding of the illustration - int decorPaddingTop = a.getDimensionPixelSize( - R.styleable.SuwSetupWizardLayout_suwDecorPaddingTop, -1); - if (decorPaddingTop == -1) { - decorPaddingTop = getResources().getDimensionPixelSize(R.dimen.suw_decor_padding_top); - } - setDecorPaddingTop(decorPaddingTop); - - - // Set the illustration aspect ratio. See Illustration.setAspectRatio(float). This will - // override suwDecorPaddingTop if its value is not 0. - float illustrationAspectRatio = a.getFloat( - R.styleable.SuwSetupWizardLayout_suwIllustrationAspectRatio, -1f); - if (illustrationAspectRatio == -1f) { - final TypedValue out = new TypedValue(); - getResources().getValue(R.dimen.suw_illustration_aspect_ratio, out, true); - illustrationAspectRatio = out.getFloat(); - } - setIllustrationAspectRatio(illustrationAspectRatio); - - a.recycle(); - } - - @Override - protected Parcelable onSaveInstanceState() { - final Parcelable parcelable = super.onSaveInstanceState(); - final SavedState ss = new SavedState(parcelable); - ss.mIsProgressBarShown = isProgressBarShown(); - return ss; + private static final String TAG = "SetupWizardLayout"; + + public SetupWizardLayout(Context context) { + super(context, 0, 0); + init(null, R.attr.suwLayoutTheme); + } + + public SetupWizardLayout(Context context, int template) { + this(context, template, 0); + } + + public SetupWizardLayout(Context context, int template, int containerId) { + super(context, template, containerId); + init(null, R.attr.suwLayoutTheme); + } + + public SetupWizardLayout(Context context, AttributeSet attrs) { + super(context, attrs); + init(attrs, R.attr.suwLayoutTheme); + } + + @TargetApi(VERSION_CODES.HONEYCOMB) + public SetupWizardLayout(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(attrs, defStyleAttr); + } + + // All the constructors delegate to this init method. The 3-argument constructor is not + // available in LinearLayout before v11, so call super with the exact same arguments. + private void init(AttributeSet attrs, int defStyleAttr) { + registerMixin(HeaderMixin.class, new HeaderMixin(this, attrs, defStyleAttr)); + registerMixin(ProgressBarMixin.class, new ProgressBarMixin(this)); + registerMixin(NavigationBarMixin.class, new NavigationBarMixin(this)); + final RequireScrollMixin requireScrollMixin = new RequireScrollMixin(this); + registerMixin(RequireScrollMixin.class, requireScrollMixin); + + final ScrollView scrollView = getScrollView(); + if (scrollView != null) { + requireScrollMixin.setScrollHandlingDelegate( + new ScrollViewScrollHandlingDelegate(requireScrollMixin, scrollView)); + } + + final TypedArray a = + getContext() + .obtainStyledAttributes(attrs, R.styleable.SuwSetupWizardLayout, defStyleAttr, 0); + + // Set the background from XML, either directly or built from a bitmap tile + final Drawable background = a.getDrawable(R.styleable.SuwSetupWizardLayout_suwBackground); + if (background != null) { + setLayoutBackground(background); + } else { + final Drawable backgroundTile = + a.getDrawable(R.styleable.SuwSetupWizardLayout_suwBackgroundTile); + if (backgroundTile != null) { + setBackgroundTile(backgroundTile); + } + } + + // Set the illustration from XML, either directly or built from image + horizontal tile + final Drawable illustration = a.getDrawable(R.styleable.SuwSetupWizardLayout_suwIllustration); + if (illustration != null) { + setIllustration(illustration); + } else { + final Drawable illustrationImage = + a.getDrawable(R.styleable.SuwSetupWizardLayout_suwIllustrationImage); + final Drawable horizontalTile = + a.getDrawable(R.styleable.SuwSetupWizardLayout_suwIllustrationHorizontalTile); + if (illustrationImage != null && horizontalTile != null) { + setIllustration(illustrationImage, horizontalTile); + } + } + + // Set the top padding of the illustration + int decorPaddingTop = + a.getDimensionPixelSize(R.styleable.SuwSetupWizardLayout_suwDecorPaddingTop, -1); + if (decorPaddingTop == -1) { + decorPaddingTop = getResources().getDimensionPixelSize(R.dimen.suw_decor_padding_top); + } + setDecorPaddingTop(decorPaddingTop); + + // Set the illustration aspect ratio. See Illustration.setAspectRatio(float). This will + // override suwDecorPaddingTop if its value is not 0. + float illustrationAspectRatio = + a.getFloat(R.styleable.SuwSetupWizardLayout_suwIllustrationAspectRatio, -1f); + if (illustrationAspectRatio == -1f) { + final TypedValue out = new TypedValue(); + getResources().getValue(R.dimen.suw_illustration_aspect_ratio, out, true); + illustrationAspectRatio = out.getFloat(); + } + setIllustrationAspectRatio(illustrationAspectRatio); + + a.recycle(); + } + + @Override + protected Parcelable onSaveInstanceState() { + final Parcelable parcelable = super.onSaveInstanceState(); + final SavedState ss = new SavedState(parcelable); + ss.isProgressBarShown = isProgressBarShown(); + return ss; + } + + @Override + protected void onRestoreInstanceState(Parcelable state) { + if (!(state instanceof SavedState)) { + Log.w(TAG, "Ignoring restore instance state " + state); + super.onRestoreInstanceState(state); + return; + } + + final SavedState ss = (SavedState) state; + super.onRestoreInstanceState(ss.getSuperState()); + final boolean isProgressBarShown = ss.isProgressBarShown; + setProgressBarShown(isProgressBarShown); + } + + @Override + protected View onInflateTemplate(LayoutInflater inflater, int template) { + if (template == 0) { + template = R.layout.suw_template; + } + return inflateTemplate(inflater, R.style.SuwThemeMaterial_Light, template); + } + + @Override + protected ViewGroup findContainer(int containerId) { + if (containerId == 0) { + containerId = R.id.suw_layout_content; + } + return super.findContainer(containerId); + } + + public NavigationBar getNavigationBar() { + return getMixin(NavigationBarMixin.class).getNavigationBar(); + } + + public ScrollView getScrollView() { + final View view = findManagedViewById(R.id.suw_bottom_scroll_view); + return view instanceof ScrollView ? (ScrollView) view : null; + } + + public void requireScrollToBottom() { + final RequireScrollMixin requireScrollMixin = getMixin(RequireScrollMixin.class); + final NavigationBar navigationBar = getNavigationBar(); + if (navigationBar != null) { + requireScrollMixin.requireScrollWithNavigationBar(navigationBar); + } else { + Log.e(TAG, "Cannot require scroll. Navigation bar is null."); + } + } + + public void setHeaderText(int title) { + getMixin(HeaderMixin.class).setText(title); + } + + public void setHeaderText(CharSequence title) { + getMixin(HeaderMixin.class).setText(title); + } + + public CharSequence getHeaderText() { + return getMixin(HeaderMixin.class).getText(); + } + + public TextView getHeaderTextView() { + return getMixin(HeaderMixin.class).getTextView(); + } + + /** + * Set the illustration of the layout. The drawable will be applied as is, and the bounds will be + * set as implemented in {@link com.android.setupwizardlib.view.Illustration}. To create a + * suitable drawable from an asset and a horizontal repeating tile, use {@link + * #setIllustration(int, int)} instead. + * + * @param drawable The drawable specifying the illustration. + */ + public void setIllustration(Drawable drawable) { + final View view = findManagedViewById(R.id.suw_layout_decor); + if (view instanceof Illustration) { + final Illustration illustration = (Illustration) view; + illustration.setIllustration(drawable); + } + } + + /** + * Set the illustration of the layout, which will be created asset and the horizontal tile as + * suitable. On phone layouts (not sw600dp), the asset will be scaled, maintaining aspect ratio. + * On tablets (sw600dp), the assets will always have 256dp height and the rest of the illustration + * area that the asset doesn't fill will be covered by the horizontalTile. + * + * @param asset Resource ID of the illustration asset. + * @param horizontalTile Resource ID of the horizontally repeating tile for tablet layout. + */ + public void setIllustration(int asset, int horizontalTile) { + final View view = findManagedViewById(R.id.suw_layout_decor); + if (view instanceof Illustration) { + final Illustration illustration = (Illustration) view; + final Drawable illustrationDrawable = getIllustration(asset, horizontalTile); + illustration.setIllustration(illustrationDrawable); + } + } + + private void setIllustration(Drawable asset, Drawable horizontalTile) { + final View view = findManagedViewById(R.id.suw_layout_decor); + if (view instanceof Illustration) { + final Illustration illustration = (Illustration) view; + final Drawable illustrationDrawable = getIllustration(asset, horizontalTile); + illustration.setIllustration(illustrationDrawable); + } + } + + /** + * Sets the aspect ratio of the illustration. This will be the space (padding top) reserved above + * the header text. This will override the padding top of the illustration. + * + * @param aspectRatio The aspect ratio + * @see com.android.setupwizardlib.view.Illustration#setAspectRatio(float) + */ + public void setIllustrationAspectRatio(float aspectRatio) { + final View view = findManagedViewById(R.id.suw_layout_decor); + if (view instanceof Illustration) { + final Illustration illustration = (Illustration) view; + illustration.setAspectRatio(aspectRatio); + } + } + + /** + * Set the top padding of the decor view. If the decor is an Illustration and the aspect ratio is + * set, this value will be overridden. + * + * <p>Note: Currently the default top padding for tablet landscape is 128dp, which is the offset + * of the card from the top. This is likely to change in future versions so this value aligns with + * the height of the illustration instead. + * + * @param paddingTop The top padding in pixels. + */ + public void setDecorPaddingTop(int paddingTop) { + final View view = findManagedViewById(R.id.suw_layout_decor); + if (view != null) { + view.setPadding( + view.getPaddingLeft(), paddingTop, view.getPaddingRight(), view.getPaddingBottom()); + } + } + + /** + * Set the background of the layout, which is expected to be able to extend infinitely. If it is a + * bitmap tile and you want it to repeat, use {@link #setBackgroundTile(int)} instead. + */ + public void setLayoutBackground(Drawable background) { + final View view = findManagedViewById(R.id.suw_layout_decor); + if (view != null) { + //noinspection deprecation + view.setBackgroundDrawable(background); + } + } + + /** + * Set the background of the layout to a repeating bitmap tile. To use a different kind of + * drawable, use {@link #setLayoutBackground(android.graphics.drawable.Drawable)} instead. + */ + public void setBackgroundTile(int backgroundTile) { + final Drawable backgroundTileDrawable = getContext().getResources().getDrawable(backgroundTile); + setBackgroundTile(backgroundTileDrawable); + } + + private void setBackgroundTile(Drawable backgroundTile) { + if (backgroundTile instanceof BitmapDrawable) { + ((BitmapDrawable) backgroundTile).setTileModeXY(TileMode.REPEAT, TileMode.REPEAT); + } + setLayoutBackground(backgroundTile); + } + + private Drawable getIllustration(int asset, int horizontalTile) { + final Context context = getContext(); + final Drawable assetDrawable = context.getResources().getDrawable(asset); + final Drawable tile = context.getResources().getDrawable(horizontalTile); + return getIllustration(assetDrawable, tile); + } + + @SuppressLint("RtlHardcoded") + private Drawable getIllustration(Drawable asset, Drawable horizontalTile) { + final Context context = getContext(); + if (context.getResources().getBoolean(R.bool.suwUseTabletLayout)) { + // If it is a "tablet" (sw600dp), create a LayerDrawable with the horizontal tile. + if (horizontalTile instanceof BitmapDrawable) { + ((BitmapDrawable) horizontalTile).setTileModeX(TileMode.REPEAT); + ((BitmapDrawable) horizontalTile).setGravity(Gravity.TOP); + } + if (asset instanceof BitmapDrawable) { + // Always specify TOP | LEFT, Illustration will flip the entire LayerDrawable. + ((BitmapDrawable) asset).setGravity(Gravity.TOP | Gravity.LEFT); + } + final LayerDrawable layers = new LayerDrawable(new Drawable[] {horizontalTile, asset}); + if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { + layers.setAutoMirrored(true); + } + return layers; + } else { + // If it is a "phone" (not sw600dp), simply return the illustration + if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { + asset.setAutoMirrored(true); + } + return asset; + } + } + + public boolean isProgressBarShown() { + return getMixin(ProgressBarMixin.class).isShown(); + } + + /** + * Sets whether the progress bar below the header text is shown or not. The progress bar is a + * lazily inflated ViewStub, which means the progress bar will not actually be part of the view + * hierarchy until the first time this is set to {@code true}. + */ + public void setProgressBarShown(boolean shown) { + getMixin(ProgressBarMixin.class).setShown(shown); + } + + /** @deprecated Use {@link #setProgressBarShown(boolean)} */ + @Deprecated + public void showProgressBar() { + setProgressBarShown(true); + } + + /** @deprecated Use {@link #setProgressBarShown(boolean)} */ + @Deprecated + public void hideProgressBar() { + setProgressBarShown(false); + } + + public void setProgressBarColor(ColorStateList color) { + getMixin(ProgressBarMixin.class).setColor(color); + } + + public ColorStateList getProgressBarColor() { + return getMixin(ProgressBarMixin.class).getColor(); + } + + /* Misc */ + + protected static class SavedState extends BaseSavedState { + + boolean isProgressBarShown = false; + + public SavedState(Parcelable parcelable) { + super(parcelable); + } + + public SavedState(Parcel source) { + super(source); + isProgressBarShown = source.readInt() != 0; } @Override - protected void onRestoreInstanceState(Parcelable state) { - if (!(state instanceof SavedState)) { - Log.w(TAG, "Ignoring restore instance state " + state); - super.onRestoreInstanceState(state); - return; - } - - final SavedState ss = (SavedState) state; - super.onRestoreInstanceState(ss.getSuperState()); - final boolean isProgressBarShown = ss.mIsProgressBarShown; - setProgressBarShown(isProgressBarShown); - } - - @Override - protected View onInflateTemplate(LayoutInflater inflater, int template) { - if (template == 0) { - template = R.layout.suw_template; - } - return inflateTemplate(inflater, R.style.SuwThemeMaterial_Light, template); - } - - @Override - protected ViewGroup findContainer(int containerId) { - if (containerId == 0) { - containerId = R.id.suw_layout_content; - } - return super.findContainer(containerId); - } - - public NavigationBar getNavigationBar() { - return getMixin(NavigationBarMixin.class).getNavigationBar(); - } - - public ScrollView getScrollView() { - final View view = findManagedViewById(R.id.suw_bottom_scroll_view); - return view instanceof ScrollView ? (ScrollView) view : null; - } - - public void requireScrollToBottom() { - final RequireScrollMixin requireScrollMixin = getMixin(RequireScrollMixin.class); - final NavigationBar navigationBar = getNavigationBar(); - if (navigationBar != null) { - requireScrollMixin.requireScrollWithNavigationBar(navigationBar); - } else { - Log.e(TAG, "Cannot require scroll. Navigation bar is null."); - } - } - - public void setHeaderText(int title) { - getMixin(HeaderMixin.class).setText(title); - } - - public void setHeaderText(CharSequence title) { - getMixin(HeaderMixin.class).setText(title); - } - - public CharSequence getHeaderText() { - return getMixin(HeaderMixin.class).getText(); - } - - public TextView getHeaderTextView() { - return getMixin(HeaderMixin.class).getTextView(); - } - - /** - * Set the illustration of the layout. The drawable will be applied as is, and the bounds will - * be set as implemented in {@link com.android.setupwizardlib.view.Illustration}. To create - * a suitable drawable from an asset and a horizontal repeating tile, use - * {@link #setIllustration(int, int)} instead. - * - * @param drawable The drawable specifying the illustration. - */ - public void setIllustration(Drawable drawable) { - final View view = findManagedViewById(R.id.suw_layout_decor); - if (view instanceof Illustration) { - final Illustration illustration = (Illustration) view; - illustration.setIllustration(drawable); - } + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeInt(isProgressBarShown ? 1 : 0); } - /** - * Set the illustration of the layout, which will be created asset and the horizontal tile as - * suitable. On phone layouts (not sw600dp), the asset will be scaled, maintaining aspect ratio. - * On tablets (sw600dp), the assets will always have 256dp height and the rest of the - * illustration area that the asset doesn't fill will be covered by the horizontalTile. - * - * @param asset Resource ID of the illustration asset. - * @param horizontalTile Resource ID of the horizontally repeating tile for tablet layout. - */ - public void setIllustration(int asset, int horizontalTile) { - final View view = findManagedViewById(R.id.suw_layout_decor); - if (view instanceof Illustration) { - final Illustration illustration = (Illustration) view; - final Drawable illustrationDrawable = getIllustration(asset, horizontalTile); - illustration.setIllustration(illustrationDrawable); - } - } - - private void setIllustration(Drawable asset, Drawable horizontalTile) { - final View view = findManagedViewById(R.id.suw_layout_decor); - if (view instanceof Illustration) { - final Illustration illustration = (Illustration) view; - final Drawable illustrationDrawable = getIllustration(asset, horizontalTile); - illustration.setIllustration(illustrationDrawable); - } - } - - /** - * Sets the aspect ratio of the illustration. This will be the space (padding top) reserved - * above the header text. This will override the padding top of the illustration. - * - * @param aspectRatio The aspect ratio - * @see com.android.setupwizardlib.view.Illustration#setAspectRatio(float) - */ - public void setIllustrationAspectRatio(float aspectRatio) { - final View view = findManagedViewById(R.id.suw_layout_decor); - if (view instanceof Illustration) { - final Illustration illustration = (Illustration) view; - illustration.setAspectRatio(aspectRatio); - } - } + public static final Parcelable.Creator<SavedState> CREATOR = + new Parcelable.Creator<SavedState>() { - /** - * Set the top padding of the decor view. If the decor is an Illustration and the aspect ratio - * is set, this value will be overridden. - * - * <p>Note: Currently the default top padding for tablet landscape is 128dp, which is the offset - * of the card from the top. This is likely to change in future versions so this value aligns - * with the height of the illustration instead. - * - * @param paddingTop The top padding in pixels. - */ - public void setDecorPaddingTop(int paddingTop) { - final View view = findManagedViewById(R.id.suw_layout_decor); - if (view != null) { - view.setPadding(view.getPaddingLeft(), paddingTop, view.getPaddingRight(), - view.getPaddingBottom()); - } - } - - /** - * Set the background of the layout, which is expected to be able to extend infinitely. If it is - * a bitmap tile and you want it to repeat, use {@link #setBackgroundTile(int)} instead. - */ - public void setLayoutBackground(Drawable background) { - final View view = findManagedViewById(R.id.suw_layout_decor); - if (view != null) { - //noinspection deprecation - view.setBackgroundDrawable(background); - } - } - - /** - * Set the background of the layout to a repeating bitmap tile. To use a different kind of - * drawable, use {@link #setLayoutBackground(android.graphics.drawable.Drawable)} instead. - */ - public void setBackgroundTile(int backgroundTile) { - final Drawable backgroundTileDrawable = - getContext().getResources().getDrawable(backgroundTile); - setBackgroundTile(backgroundTileDrawable); - } + @Override + public SavedState createFromParcel(Parcel parcel) { + return new SavedState(parcel); + } - private void setBackgroundTile(Drawable backgroundTile) { - if (backgroundTile instanceof BitmapDrawable) { - ((BitmapDrawable) backgroundTile).setTileModeXY(TileMode.REPEAT, TileMode.REPEAT); - } - setLayoutBackground(backgroundTile); - } - - private Drawable getIllustration(int asset, int horizontalTile) { - final Context context = getContext(); - final Drawable assetDrawable = context.getResources().getDrawable(asset); - final Drawable tile = context.getResources().getDrawable(horizontalTile); - return getIllustration(assetDrawable, tile); - } - - @SuppressLint("RtlHardcoded") - private Drawable getIllustration(Drawable asset, Drawable horizontalTile) { - final Context context = getContext(); - if (context.getResources().getBoolean(R.bool.suwUseTabletLayout)) { - // If it is a "tablet" (sw600dp), create a LayerDrawable with the horizontal tile. - if (horizontalTile instanceof BitmapDrawable) { - ((BitmapDrawable) horizontalTile).setTileModeX(TileMode.REPEAT); - ((BitmapDrawable) horizontalTile).setGravity(Gravity.TOP); - } - if (asset instanceof BitmapDrawable) { - // Always specify TOP | LEFT, Illustration will flip the entire LayerDrawable. - ((BitmapDrawable) asset).setGravity(Gravity.TOP | Gravity.LEFT); - } - final LayerDrawable layers = - new LayerDrawable(new Drawable[] { horizontalTile, asset }); - if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { - layers.setAutoMirrored(true); - } - return layers; - } else { - // If it is a "phone" (not sw600dp), simply return the illustration - if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { - asset.setAutoMirrored(true); - } - return asset; - } - } - - public boolean isProgressBarShown() { - return getMixin(ProgressBarMixin.class).isShown(); - } - - /** - * Sets whether the progress bar below the header text is shown or not. The progress bar is - * a lazily inflated ViewStub, which means the progress bar will not actually be part of the - * view hierarchy until the first time this is set to {@code true}. - */ - public void setProgressBarShown(boolean shown) { - getMixin(ProgressBarMixin.class).setShown(shown); - } - - /** - * @deprecated Use {@link #setProgressBarShown(boolean)} - */ - @Deprecated - public void showProgressBar() { - setProgressBarShown(true); - } - - /** - * @deprecated Use {@link #setProgressBarShown(boolean)} - */ - @Deprecated - public void hideProgressBar() { - setProgressBarShown(false); - } - - public void setProgressBarColor(ColorStateList color) { - getMixin(ProgressBarMixin.class).setColor(color); - } - - public ColorStateList getProgressBarColor() { - return getMixin(ProgressBarMixin.class).getColor(); - } - - /* Misc */ - - protected static class SavedState extends BaseSavedState { - - boolean mIsProgressBarShown = false; - - public SavedState(Parcelable parcelable) { - super(parcelable); - } - - public SavedState(Parcel source) { - super(source); - mIsProgressBarShown = source.readInt() != 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeInt(mIsProgressBarShown ? 1 : 0); - } - - public static final Parcelable.Creator<SavedState> CREATOR = - new Parcelable.Creator<SavedState>() { - - @Override - public SavedState createFromParcel(Parcel parcel) { - return new SavedState(parcel); - } - - @Override - public SavedState[] newArray(int size) { - return new SavedState[size]; - } - }; - } + @Override + public SavedState[] newArray(int size) { + return new SavedState[size]; + } + }; + } } diff --git a/library/main/src/com/android/setupwizardlib/SetupWizardListLayout.java b/library/main/src/com/android/setupwizardlib/SetupWizardListLayout.java index 050d566..f1c7e11 100644 --- a/library/main/src/com/android/setupwizardlib/SetupWizardListLayout.java +++ b/library/main/src/com/android/setupwizardlib/SetupWizardListLayout.java @@ -26,141 +26,128 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; - import com.android.setupwizardlib.template.ListMixin; import com.android.setupwizardlib.template.ListViewScrollHandlingDelegate; import com.android.setupwizardlib.template.RequireScrollMixin; public class SetupWizardListLayout extends SetupWizardLayout { - private static final String TAG = "SetupWizardListLayout"; - - private ListMixin mListMixin; - - public SetupWizardListLayout(Context context) { - this(context, 0, 0); - } - - public SetupWizardListLayout(Context context, int template) { - this(context, template, 0); - } - - public SetupWizardListLayout(Context context, int template, int containerId) { - super(context, template, containerId); - init(context, null, 0); - } - - public SetupWizardListLayout(Context context, AttributeSet attrs) { - super(context, attrs); - init(context, attrs, 0); - } - - @TargetApi(VERSION_CODES.HONEYCOMB) - public SetupWizardListLayout(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(context, attrs, defStyleAttr); - } - - private void init(Context context, AttributeSet attrs, int defStyleAttr) { - mListMixin = new ListMixin(this, attrs, defStyleAttr); - registerMixin(ListMixin.class, mListMixin); - - final RequireScrollMixin requireScrollMixin = getMixin(RequireScrollMixin.class); - requireScrollMixin.setScrollHandlingDelegate( - new ListViewScrollHandlingDelegate(requireScrollMixin, getListView())); - } - - @Override - protected View onInflateTemplate(LayoutInflater inflater, int template) { - if (template == 0) { - template = R.layout.suw_list_template; - } - return super.onInflateTemplate(inflater, template); - } - - @Override - protected ViewGroup findContainer(int containerId) { - if (containerId == 0) { - containerId = android.R.id.list; - } - return super.findContainer(containerId); - } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - super.onLayout(changed, left, top, right, bottom); - mListMixin.onLayout(); - } - - public ListView getListView() { - return mListMixin.getListView(); - } - - public void setAdapter(ListAdapter adapter) { - mListMixin.setAdapter(adapter); - } - - public ListAdapter getAdapter() { - return mListMixin.getAdapter(); - } - - /** - * Sets the start inset of the divider. This will use the default divider drawable set in the - * theme and inset it {@code inset} pixels to the right (or left in RTL layouts). - * - * @param inset The number of pixels to inset on the "start" side of the list divider. Typically - * this will be either {@code @dimen/suw_items_icon_divider_inset} or - * {@code @dimen/suw_items_text_divider_inset}. - * - * @see ListMixin#setDividerInset(int) - * @deprecated Use {@link #setDividerInsets(int, int)} instead. - */ - @Deprecated - public void setDividerInset(int inset) { - mListMixin.setDividerInset(inset); - } - - /** - * Sets the start inset of the divider. This will use the default divider drawable set in the - * theme and apply insets to it. - * - * @param start The number of pixels to inset on the "start" side of the list divider. Typically - * this will be either {@code @dimen/suw_items_icon_divider_inset} or - * {@code @dimen/suw_items_text_divider_inset}. - * @param end The number of pixels to inset on the "end" side of the list divider. - * - * @see ListMixin#setDividerInsets(int, int) - */ - public void setDividerInsets(int start, int end) { - mListMixin.setDividerInsets(start, end); - } - - /** - * @deprecated Use {@link #getDividerInsetStart()} instead. - */ - @Deprecated - public int getDividerInset() { - return mListMixin.getDividerInset(); - } - - /** - * @see ListMixin#getDividerInsetStart() - */ - public int getDividerInsetStart() { - return mListMixin.getDividerInsetStart(); - } - - /** - * @see ListMixin#getDividerInsetEnd() - */ - public int getDividerInsetEnd() { - return mListMixin.getDividerInsetEnd(); - } - - /** - * @see ListMixin#getDivider() - */ - public Drawable getDivider() { - return mListMixin.getDivider(); - } + private ListMixin listMixin; + + public SetupWizardListLayout(Context context) { + this(context, 0, 0); + } + + public SetupWizardListLayout(Context context, int template) { + this(context, template, 0); + } + + public SetupWizardListLayout(Context context, int template, int containerId) { + super(context, template, containerId); + init(null, 0); + } + + public SetupWizardListLayout(Context context, AttributeSet attrs) { + super(context, attrs); + init(attrs, 0); + } + + @TargetApi(VERSION_CODES.HONEYCOMB) + public SetupWizardListLayout(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(attrs, defStyleAttr); + } + + private void init(AttributeSet attrs, int defStyleAttr) { + listMixin = new ListMixin(this, attrs, defStyleAttr); + registerMixin(ListMixin.class, listMixin); + + final RequireScrollMixin requireScrollMixin = getMixin(RequireScrollMixin.class); + requireScrollMixin.setScrollHandlingDelegate( + new ListViewScrollHandlingDelegate(requireScrollMixin, getListView())); + } + + @Override + protected View onInflateTemplate(LayoutInflater inflater, int template) { + if (template == 0) { + template = R.layout.suw_list_template; + } + return super.onInflateTemplate(inflater, template); + } + + @Override + protected ViewGroup findContainer(int containerId) { + if (containerId == 0) { + containerId = android.R.id.list; + } + return super.findContainer(containerId); + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + super.onLayout(changed, left, top, right, bottom); + listMixin.onLayout(); + } + + public ListView getListView() { + return listMixin.getListView(); + } + + public void setAdapter(ListAdapter adapter) { + listMixin.setAdapter(adapter); + } + + public ListAdapter getAdapter() { + return listMixin.getAdapter(); + } + + /** + * Sets the start inset of the divider. This will use the default divider drawable set in the + * theme and inset it {@code inset} pixels to the right (or left in RTL layouts). + * + * @param inset The number of pixels to inset on the "start" side of the list divider. Typically + * this will be either {@code @dimen/suw_items_icon_divider_inset} or + * {@code @dimen/suw_items_text_divider_inset}. + * @see ListMixin#setDividerInset(int) + * @deprecated Use {@link #setDividerInsets(int, int)} instead. + */ + @Deprecated + public void setDividerInset(int inset) { + listMixin.setDividerInset(inset); + } + + /** + * Sets the start inset of the divider. This will use the default divider drawable set in the + * theme and apply insets to it. + * + * @param start The number of pixels to inset on the "start" side of the list divider. Typically + * this will be either {@code @dimen/suw_items_icon_divider_inset} or + * {@code @dimen/suw_items_text_divider_inset}. + * @param end The number of pixels to inset on the "end" side of the list divider. + * @see ListMixin#setDividerInsets(int, int) + */ + public void setDividerInsets(int start, int end) { + listMixin.setDividerInsets(start, end); + } + + /** @deprecated Use {@link #getDividerInsetStart()} instead. */ + @Deprecated + public int getDividerInset() { + return listMixin.getDividerInset(); + } + + /** @see ListMixin#getDividerInsetStart() */ + public int getDividerInsetStart() { + return listMixin.getDividerInsetStart(); + } + + /** @see ListMixin#getDividerInsetEnd() */ + public int getDividerInsetEnd() { + return listMixin.getDividerInsetEnd(); + } + + /** @see ListMixin#getDivider() */ + public Drawable getDivider() { + return listMixin.getDivider(); + } } diff --git a/library/main/src/com/android/setupwizardlib/TemplateLayout.java b/library/main/src/com/android/setupwizardlib/TemplateLayout.java index 0108880..c53e176 100644 --- a/library/main/src/com/android/setupwizardlib/TemplateLayout.java +++ b/library/main/src/com/android/setupwizardlib/TemplateLayout.java @@ -20,256 +20,249 @@ import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.os.Build.VERSION_CODES; +import androidx.annotation.Keep; +import androidx.annotation.LayoutRes; +import androidx.annotation.StyleRes; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.FrameLayout; - -import androidx.annotation.Keep; -import androidx.annotation.LayoutRes; -import androidx.annotation.StyleRes; - import com.android.setupwizardlib.template.Mixin; import com.android.setupwizardlib.util.FallbackThemeWrapper; - import java.util.HashMap; import java.util.Map; /** - * A generic template class that inflates a template, provided in the constructor or in - * {@code android:layout} through XML, and adds its children to a "container" in the template. When + * A generic template class that inflates a template, provided in the constructor or in {@code + * android:layout} through XML, and adds its children to a "container" in the template. When * inflating this layout from XML, the {@code android:layout} and {@code suwContainer} attributes * are required. */ public class TemplateLayout extends FrameLayout { - /** - * The container of the actual content. This will be a view in the template, which child views - * will be added to when {@link #addView(View)} is called. - */ - private ViewGroup mContainer; - - private Map<Class<? extends Mixin>, Mixin> mMixins = new HashMap<>(); + /** + * The container of the actual content. This will be a view in the template, which child views + * will be added to when {@link #addView(View)} is called. + */ + private ViewGroup container; - public TemplateLayout(Context context, int template, int containerId) { - super(context); - init(template, containerId, null, R.attr.suwLayoutTheme); - } + private final Map<Class<? extends Mixin>, Mixin> mixins = new HashMap<>(); - public TemplateLayout(Context context, AttributeSet attrs) { - super(context, attrs); - init(0, 0, attrs, R.attr.suwLayoutTheme); - } + public TemplateLayout(Context context, int template, int containerId) { + super(context); + init(template, containerId, null, R.attr.suwLayoutTheme); + } - @TargetApi(VERSION_CODES.HONEYCOMB) - public TemplateLayout(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(0, 0, attrs, defStyleAttr); - } + public TemplateLayout(Context context, AttributeSet attrs) { + super(context, attrs); + init(0, 0, attrs, R.attr.suwLayoutTheme); + } - // All the constructors delegate to this init method. The 3-argument constructor is not - // available in LinearLayout before v11, so call super with the exact same arguments. - private void init(int template, int containerId, AttributeSet attrs, int defStyleAttr) { - final TypedArray a = getContext().obtainStyledAttributes(attrs, - R.styleable.SuwTemplateLayout, defStyleAttr, 0); - if (template == 0) { - template = a.getResourceId(R.styleable.SuwTemplateLayout_android_layout, 0); - } - if (containerId == 0) { - containerId = a.getResourceId(R.styleable.SuwTemplateLayout_suwContainer, 0); - } - inflateTemplate(template, containerId); + @TargetApi(VERSION_CODES.HONEYCOMB) + public TemplateLayout(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(0, 0, attrs, defStyleAttr); + } - a.recycle(); + // All the constructors delegate to this init method. The 3-argument constructor is not + // available in LinearLayout before v11, so call super with the exact same arguments. + private void init(int template, int containerId, AttributeSet attrs, int defStyleAttr) { + final TypedArray a = + getContext().obtainStyledAttributes(attrs, R.styleable.SuwTemplateLayout, defStyleAttr, 0); + if (template == 0) { + template = a.getResourceId(R.styleable.SuwTemplateLayout_android_layout, 0); } - - /** - * Registers a mixin with a given class. This method should be called in the constructor. - * - * @param cls The class to register the mixin. In most cases, {@code cls} is the same as - * {@code mixin.getClass()}, but {@code cls} can also be a super class of that. In - * the latter case the the mixin must be retrieved using {@code cls} in - * {@link #getMixin(Class)}, not the subclass. - * @param mixin The mixin to be registered. - * @param <M> The class of the mixin to register. This is the same as {@code cls} - */ - protected <M extends Mixin> void registerMixin(Class<M> cls, M mixin) { - mMixins.put(cls, mixin); + if (containerId == 0) { + containerId = a.getResourceId(R.styleable.SuwTemplateLayout_suwContainer, 0); } + inflateTemplate(template, containerId); - /** - * Same as {@link android.view.View#findViewById(int)}, but may include views that are managed - * by this view but not currently added to the view hierarchy. e.g. recycler view or list view - * headers that are not currently shown. - */ - // Returning generic type is the common pattern used for findViewBy* methods - @SuppressWarnings("TypeParameterUnusedInFormals") - public <T extends View> T findManagedViewById(int id) { - return findViewById(id); - } + a.recycle(); + } - /** - * Get a {@link Mixin} from this template registered earlier in - * {@link #registerMixin(Class, Mixin)}. - * - * @param cls The class marker of Mixin being requested. The actual Mixin returned may be a - * subclass of this marker. Note that this must be the same class as registered in - * {@link #registerMixin(Class, Mixin)}, which is not necessarily the - * same as the concrete class of the instance returned by this method. - * @param <M> The type of the class marker. - * @return The mixin marked by {@code cls}, or null if the template does not have a matching - * mixin. - */ - @SuppressWarnings("unchecked") - public <M extends Mixin> M getMixin(Class<M> cls) { - return (M) mMixins.get(cls); - } + /** + * Registers a mixin with a given class. This method should be called in the constructor. + * + * @param cls The class to register the mixin. In most cases, {@code cls} is the same as {@code + * mixin.getClass()}, but {@code cls} can also be a super class of that. In the latter case + * the mixin must be retrieved using {@code cls} in {@link #getMixin(Class)}, not the + * subclass. + * @param mixin The mixin to be registered. + * @param <M> The class of the mixin to register. This is the same as {@code cls} + */ + protected <M extends Mixin> void registerMixin(Class<M> cls, M mixin) { + mixins.put(cls, mixin); + } - @Override - public void addView(View child, int index, ViewGroup.LayoutParams params) { - mContainer.addView(child, index, params); - } + /** + * Same as {@link android.view.View#findViewById(int)}, but may include views that are managed by + * this view but not currently added to the view hierarchy. e.g. recycler view or list view + * headers that are not currently shown. + */ + // Returning generic type is the common pattern used for findViewBy* methods + @SuppressWarnings("TypeParameterUnusedInFormals") + public <T extends View> T findManagedViewById(int id) { + return findViewById(id); + } - private void addViewInternal(View child) { - super.addView(child, -1, generateDefaultLayoutParams()); - } + /** + * Get a {@link Mixin} from this template registered earlier in {@link #registerMixin(Class, + * Mixin)}. + * + * @param cls The class marker of Mixin being requested. The actual Mixin returned may be a + * subclass of this marker. Note that this must be the same class as registered in {@link + * #registerMixin(Class, Mixin)}, which is not necessarily the same as the concrete class of + * the instance returned by this method. + * @param <M> The type of the class marker. + * @return The mixin marked by {@code cls}, or null if the template does not have a matching + * mixin. + */ + @SuppressWarnings("unchecked") + public <M extends Mixin> M getMixin(Class<M> cls) { + return (M) mixins.get(cls); + } - private void inflateTemplate(int templateResource, int containerId) { - final LayoutInflater inflater = LayoutInflater.from(getContext()); - final View templateRoot = onInflateTemplate(inflater, templateResource); - addViewInternal(templateRoot); + @Override + public void addView(View child, int index, ViewGroup.LayoutParams params) { + container.addView(child, index, params); + } - mContainer = findContainer(containerId); - if (mContainer == null) { - throw new IllegalArgumentException("Container cannot be null in TemplateLayout"); - } - onTemplateInflated(); - } + private void addViewInternal(View child) { + super.addView(child, -1, generateDefaultLayoutParams()); + } - /** - * This method inflates the template. Subclasses can override this method to customize the - * template inflation, or change to a different default template. The root of the inflated - * layout should be returned, and not added to the view hierarchy. - * - * @param inflater A LayoutInflater to inflate the template. - * @param template The resource ID of the template to be inflated, or 0 if no template is - * specified. - * @return Root of the inflated layout. - */ - protected View onInflateTemplate(LayoutInflater inflater, @LayoutRes int template) { - return inflateTemplate(inflater, 0, template); - } + private void inflateTemplate(int templateResource, int containerId) { + final LayoutInflater inflater = LayoutInflater.from(getContext()); + final View templateRoot = onInflateTemplate(inflater, templateResource); + addViewInternal(templateRoot); - /** - * Inflate the template using the given inflater and theme. The fallback theme will be applied - * to the theme without overriding the values already defined in the theme, but simply providing - * default values for values which have not been defined. This allows templates to add - * additional required theme attributes without breaking existing clients. - * - * <p>In general, clients should still set the activity theme to the corresponding theme in - * setup wizard lib, so that the content area gets the correct styles as well. - * - * @param inflater A LayoutInflater to inflate the template. - * @param fallbackTheme A fallback theme to apply to the template. If the values defined in the - * fallback theme is already defined in the original theme, the value in - * the original theme takes precedence. - * @param template The layout template to be inflated. - * @return Root of the inflated layout. - * - * @see FallbackThemeWrapper - */ - protected final View inflateTemplate(LayoutInflater inflater, @StyleRes int fallbackTheme, - @LayoutRes int template) { - if (template == 0) { - throw new IllegalArgumentException("android:layout not specified for TemplateLayout"); - } - if (fallbackTheme != 0) { - inflater = LayoutInflater.from( - new FallbackThemeWrapper(inflater.getContext(), fallbackTheme)); - } - return inflater.inflate(template, this, false); + container = findContainer(containerId); + if (container == null) { + throw new IllegalArgumentException("Container cannot be null in TemplateLayout"); } + onTemplateInflated(); + } - protected ViewGroup findContainer(int containerId) { - if (containerId == 0) { - // Maintain compatibility with the deprecated way of specifying container ID. - containerId = getContainerId(); - } - return (ViewGroup) findViewById(containerId); + /** + * Inflate the template using the given inflater and theme. The fallback theme will be applied to + * the theme without overriding the values already defined in the theme, but simply providing + * default values for values which have not been defined. This allows templates to add additional + * required theme attributes without breaking existing clients. + * + * <p>In general, clients should still set the activity theme to the corresponding theme in setup + * wizard lib, so that the content area gets the correct styles as well. + * + * @param inflater A LayoutInflater to inflate the template. + * @param fallbackTheme A fallback theme to apply to the template. If the values defined in the + * fallback theme is already defined in the original theme, the value in the original theme + * takes precedence. + * @param template The layout template to be inflated. + * @return Root of the inflated layout. + * @see FallbackThemeWrapper + */ + protected final View inflateTemplate( + LayoutInflater inflater, @StyleRes int fallbackTheme, @LayoutRes int template) { + if (template == 0) { + throw new IllegalArgumentException("android:layout not specified for TemplateLayout"); } - - /** - * This is called after the template has been inflated and added to the view hierarchy. - * Subclasses can implement this method to modify the template as necessary, such as caching - * views retrieved from findViewById, or other view operations that need to be done in code. - * You can think of this as {@link View#onFinishInflate()} but for inflation of the - * template instead of for child views. - */ - protected void onTemplateInflated() { + if (fallbackTheme != 0) { + inflater = + LayoutInflater.from(new FallbackThemeWrapper(inflater.getContext(), fallbackTheme)); } + return inflater.inflate(template, this, false); + } + + /** + * This method inflates the template. Subclasses can override this method to customize the + * template inflation, or change to a different default template. The root of the inflated layout + * should be returned, and not added to the view hierarchy. + * + * @param inflater A LayoutInflater to inflate the template. + * @param template The resource ID of the template to be inflated, or 0 if no template is + * specified. + * @return Root of the inflated layout. + */ + protected View onInflateTemplate(LayoutInflater inflater, @LayoutRes int template) { + return inflateTemplate(inflater, 0, template); + } - /** - * @return ID of the default container for this layout. This will be used to find the container - * ViewGroup, which all children views of this layout will be placed in. - * @deprecated Override {@link #findContainer(int)} instead. - */ - @Deprecated - protected int getContainerId() { - return 0; + protected ViewGroup findContainer(int containerId) { + if (containerId == 0) { + // Maintain compatibility with the deprecated way of specifying container ID. + containerId = getContainerId(); } + return (ViewGroup) findViewById(containerId); + } - /* Animator support */ + /** + * This is called after the template has been inflated and added to the view hierarchy. Subclasses + * can implement this method to modify the template as necessary, such as caching views retrieved + * from findViewById, or other view operations that need to be done in code. You can think of this + * as {@link View#onFinishInflate()} but for inflation of the template instead of for child views. + */ + protected void onTemplateInflated() {} - private float mXFraction; - private ViewTreeObserver.OnPreDrawListener mPreDrawListener; + /** + * @return ID of the default container for this layout. This will be used to find the container + * ViewGroup, which all children views of this layout will be placed in. + * @deprecated Override {@link #findContainer(int)} instead. + */ + @Deprecated + protected int getContainerId() { + return 0; + } - /** - * Set the X translation as a fraction of the width of this view. Make sure this method is not - * stripped out by proguard when using this with {@link android.animation.ObjectAnimator}. You - * may need to add - * <code> - * -keep @androidx.annotation.Keep class * - * </code> - * to your proguard configuration if you are seeing mysterious {@link NoSuchMethodError} at - * runtime. - */ - @Keep - @TargetApi(VERSION_CODES.HONEYCOMB) - public void setXFraction(float fraction) { - mXFraction = fraction; - final int width = getWidth(); - if (width != 0) { - setTranslationX(width * fraction); - } else { - // If we haven't done a layout pass yet, wait for one and then set the fraction before - // the draw occurs using an OnPreDrawListener. Don't call translationX until we know - // getWidth() has a reliable, non-zero value or else we will see the fragment flicker on - // screen. - if (mPreDrawListener == null) { - mPreDrawListener = new ViewTreeObserver.OnPreDrawListener() { - @Override - public boolean onPreDraw() { - getViewTreeObserver().removeOnPreDrawListener(mPreDrawListener); - setXFraction(mXFraction); - return true; - } - }; - getViewTreeObserver().addOnPreDrawListener(mPreDrawListener); - } - } - } + /* Animator support */ + + private float xFraction; + private ViewTreeObserver.OnPreDrawListener preDrawListener; - /** - * Return the X translation as a fraction of the width, as previously set in - * {@link #setXFraction(float)}. - * - * @see #setXFraction(float) - */ - @Keep - @TargetApi(VERSION_CODES.HONEYCOMB) - public float getXFraction() { - return mXFraction; + /** + * Set the X translation as a fraction of the width of this view. Make sure this method is not + * stripped out by proguard when using this with {@link android.animation.ObjectAnimator}. You may + * need to add <code> + * -keep @androidx.annotation.Keep class * + * </code> to your proguard configuration if you are seeing mysterious {@link NoSuchMethodError} + * at runtime. + */ + @Keep + @TargetApi(VERSION_CODES.HONEYCOMB) + public void setXFraction(float fraction) { + xFraction = fraction; + final int width = getWidth(); + if (width != 0) { + setTranslationX(width * fraction); + } else { + // If we haven't done a layout pass yet, wait for one and then set the fraction before + // the draw occurs using an OnPreDrawListener. Don't call translationX until we know + // getWidth() has a reliable, non-zero value or else we will see the fragment flicker on + // screen. + if (preDrawListener == null) { + preDrawListener = + new ViewTreeObserver.OnPreDrawListener() { + @Override + public boolean onPreDraw() { + getViewTreeObserver().removeOnPreDrawListener(preDrawListener); + setXFraction(xFraction); + return true; + } + }; + getViewTreeObserver().addOnPreDrawListener(preDrawListener); + } } + } + + /** + * Return the X translation as a fraction of the width, as previously set in {@link + * #setXFraction(float)}. + * + * @see #setXFraction(float) + */ + @Keep + @TargetApi(VERSION_CODES.HONEYCOMB) + public float getXFraction() { + return xFraction; + } } diff --git a/library/main/src/com/android/setupwizardlib/gesture/ConsecutiveTapsGestureDetector.java b/library/main/src/com/android/setupwizardlib/gesture/ConsecutiveTapsGestureDetector.java index f438691..2ea5288 100644 --- a/library/main/src/com/android/setupwizardlib/gesture/ConsecutiveTapsGestureDetector.java +++ b/library/main/src/com/android/setupwizardlib/gesture/ConsecutiveTapsGestureDetector.java @@ -24,95 +24,86 @@ import android.view.ViewConfiguration; /** * Helper class to detect the consective-tap gestures on a view. * - * <p/>This class is instantiated and used similar to a GestureDetector, where onTouchEvent should - * be called when there are MotionEvents this detector should know about. + * <p>This class is instantiated and used similar to a GestureDetector, where onTouchEvent should be + * called when there are MotionEvents this detector should know about. */ public final class ConsecutiveTapsGestureDetector { - public interface OnConsecutiveTapsListener { - /** - * Callback method when the user tapped on the target view X number of times. - */ - void onConsecutiveTaps(int numOfConsecutiveTaps); - } - - private final View mView; - private final OnConsecutiveTapsListener mListener; - private final int mConsecutiveTapTouchSlopSquare; - private final int mConsecutiveTapTimeout; + public interface OnConsecutiveTapsListener { + /** Callback method when the user tapped on the target view X number of times. */ + void onConsecutiveTaps(int numOfConsecutiveTaps); + } - private int mConsecutiveTapsCounter = 0; - private MotionEvent mPreviousTapEvent; + private final View view; + private final OnConsecutiveTapsListener listener; + private final int consecutiveTapTouchSlopSquare; + private final int consecutiveTapTimeout; - /** - * @param listener The listener that responds to the gesture. - * @param view The target view that associated with consecutive-tap gesture. - */ - public ConsecutiveTapsGestureDetector( - OnConsecutiveTapsListener listener, - View view) { - mListener = listener; - mView = view; - int doubleTapSlop = ViewConfiguration.get(mView.getContext()).getScaledDoubleTapSlop(); - mConsecutiveTapTouchSlopSquare = doubleTapSlop * doubleTapSlop; - mConsecutiveTapTimeout = ViewConfiguration.getDoubleTapTimeout(); - } + private int consecutiveTapsCounter = 0; + private MotionEvent previousTapEvent; - /** - * This method should be called from the relevant activity or view, typically in - * onTouchEvent, onInterceptTouchEvent or dispatchTouchEvent. - * - * @param ev The motion event - */ - public void onTouchEvent(MotionEvent ev) { - if (ev.getAction() == MotionEvent.ACTION_UP) { - Rect viewRect = new Rect(); - int[] leftTop = new int[2]; - mView.getLocationOnScreen(leftTop); - viewRect.set( - leftTop[0], - leftTop[1], - leftTop[0] + mView.getWidth(), - leftTop[1] + mView.getHeight()); - if (viewRect.contains((int) ev.getX(), (int) ev.getY())) { - if (isConsecutiveTap(ev)) { - mConsecutiveTapsCounter++; - } else { - mConsecutiveTapsCounter = 1; - } - mListener.onConsecutiveTaps(mConsecutiveTapsCounter); - } else { - // Touch outside the target view. Reset counter. - mConsecutiveTapsCounter = 0; - } + /** + * @param listener The listener that responds to the gesture. + * @param view The target view that associated with consecutive-tap gesture. + */ + public ConsecutiveTapsGestureDetector(OnConsecutiveTapsListener listener, View view) { + this.listener = listener; + this.view = view; + int doubleTapSlop = ViewConfiguration.get(this.view.getContext()).getScaledDoubleTapSlop(); + consecutiveTapTouchSlopSquare = doubleTapSlop * doubleTapSlop; + consecutiveTapTimeout = ViewConfiguration.getDoubleTapTimeout(); + } - if (mPreviousTapEvent != null) { - mPreviousTapEvent.recycle(); - } - mPreviousTapEvent = MotionEvent.obtain(ev); + /** + * This method should be called from the relevant activity or view, typically in onTouchEvent, + * onInterceptTouchEvent or dispatchTouchEvent. + * + * @param ev The motion event + */ + public void onTouchEvent(MotionEvent ev) { + if (ev.getAction() == MotionEvent.ACTION_UP) { + Rect viewRect = new Rect(); + int[] leftTop = new int[2]; + view.getLocationOnScreen(leftTop); + viewRect.set( + leftTop[0], leftTop[1], leftTop[0] + view.getWidth(), leftTop[1] + view.getHeight()); + if (viewRect.contains((int) ev.getX(), (int) ev.getY())) { + if (isConsecutiveTap(ev)) { + consecutiveTapsCounter++; + } else { + consecutiveTapsCounter = 1; } - } + listener.onConsecutiveTaps(consecutiveTapsCounter); + } else { + // Touch outside the target view. Reset counter. + consecutiveTapsCounter = 0; + } - /** - * Resets the consecutive-tap counter to zero. - */ - public void resetCounter() { - mConsecutiveTapsCounter = 0; + if (previousTapEvent != null) { + previousTapEvent.recycle(); + } + previousTapEvent = MotionEvent.obtain(ev); } + } - /** - * Returns true if the distance between consecutive tap is within - * {@link #mConsecutiveTapTouchSlopSquare}. False, otherwise. - */ - private boolean isConsecutiveTap(MotionEvent currentTapEvent) { - if (mPreviousTapEvent == null) { - return false; - } + /** Resets the consecutive-tap counter to zero. */ + public void resetCounter() { + consecutiveTapsCounter = 0; + } - double deltaX = mPreviousTapEvent.getX() - currentTapEvent.getX(); - double deltaY = mPreviousTapEvent.getY() - currentTapEvent.getY(); - long deltaTime = currentTapEvent.getEventTime() - mPreviousTapEvent.getEventTime(); - return (deltaX * deltaX + deltaY * deltaY <= mConsecutiveTapTouchSlopSquare) - && deltaTime < mConsecutiveTapTimeout; + /** + * Returns true if the distance between consecutive tap is within {@link + * #consecutiveTapTouchSlopSquare}. False, otherwise. + */ + private boolean isConsecutiveTap(MotionEvent currentTapEvent) { + if (previousTapEvent == null) { + return false; } + + double deltaX = previousTapEvent.getX() - currentTapEvent.getX(); + double deltaY = previousTapEvent.getY() - currentTapEvent.getY(); + long deltaTime = currentTapEvent.getEventTime() - previousTapEvent.getEventTime(); + return (deltaX * deltaX + deltaY * deltaY <= consecutiveTapTouchSlopSquare) + && deltaTime < consecutiveTapTimeout; + } } diff --git a/library/main/src/com/android/setupwizardlib/items/AbstractItem.java b/library/main/src/com/android/setupwizardlib/items/AbstractItem.java index 11a9939..88f9294 100644 --- a/library/main/src/com/android/setupwizardlib/items/AbstractItem.java +++ b/library/main/src/com/android/setupwizardlib/items/AbstractItem.java @@ -25,42 +25,42 @@ import android.util.AttributeSet; */ public abstract class AbstractItem extends AbstractItemHierarchy implements IItem { - public AbstractItem() { - super(); - } + public AbstractItem() { + super(); + } - public AbstractItem(Context context, AttributeSet attrs) { - super(context, attrs); - } + public AbstractItem(Context context, AttributeSet attrs) { + super(context, attrs); + } - @Override - public int getCount() { - return 1; - } + @Override + public int getCount() { + return 1; + } - @Override - public IItem getItemAt(int position) { - return this; - } + @Override + public IItem getItemAt(int position) { + return this; + } - @Override - public ItemHierarchy findItemById(int id) { - if (id == getId()) { - return this; - } - return null; + @Override + public ItemHierarchy findItemById(int id) { + if (id == getId()) { + return this; } + return null; + } - /** - * Convenience method to notify the adapter that the contents of this item has changed. This - * only includes non-structural changes. Changes that causes the item to be removed should use - * the other notification methods. - * - * @see #notifyItemRangeChanged(int, int) - * @see #notifyItemRangeInserted(int, int) - * @see #notifyItemRangeRemoved(int, int) - */ - public void notifyItemChanged() { - notifyItemRangeChanged(0, 1); - } + /** + * Convenience method to notify the adapter that the contents of this item has changed. This only + * includes non-structural changes. Changes that causes the item to be removed should use the + * other notification methods. + * + * @see #notifyItemRangeChanged(int, int) + * @see #notifyItemRangeInserted(int, int) + * @see #notifyItemRangeRemoved(int, int) + */ + public void notifyItemChanged() { + notifyItemRangeChanged(0, 1); + } } diff --git a/library/main/src/com/android/setupwizardlib/items/AbstractItemHierarchy.java b/library/main/src/com/android/setupwizardlib/items/AbstractItemHierarchy.java index 805e7af..e33cc2f 100644 --- a/library/main/src/com/android/setupwizardlib/items/AbstractItemHierarchy.java +++ b/library/main/src/com/android/setupwizardlib/items/AbstractItemHierarchy.java @@ -20,138 +20,123 @@ import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.Log; - import com.android.setupwizardlib.R; - import java.util.ArrayList; -/** - * An abstract item hierarchy; provides default implementation for ID and observers. - */ +/** An abstract item hierarchy; provides default implementation for ID and observers. */ public abstract class AbstractItemHierarchy implements ItemHierarchy { - /* static section */ + /* static section */ - private static final String TAG = "AbstractItemHierarchy"; + private static final String TAG = "AbstractItemHierarchy"; - /* non-static section */ + /* non-static section */ - private ArrayList<Observer> mObservers = new ArrayList<>(); - private int mId = 0; + private final ArrayList<Observer> observers = new ArrayList<>(); + private int id = 0; - public AbstractItemHierarchy() { - } + public AbstractItemHierarchy() {} - public AbstractItemHierarchy(Context context, AttributeSet attrs) { - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SuwAbstractItem); - mId = a.getResourceId(R.styleable.SuwAbstractItem_android_id, 0); - a.recycle(); - } + public AbstractItemHierarchy(Context context, AttributeSet attrs) { + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SuwAbstractItem); + id = a.getResourceId(R.styleable.SuwAbstractItem_android_id, 0); + a.recycle(); + } - public void setId(int id) { - mId = id; - } + public void setId(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public int getViewId() { + return getId(); + } - public int getId() { - return mId; + @Override + public void registerObserver(Observer observer) { + observers.add(observer); + } + + @Override + public void unregisterObserver(Observer observer) { + observers.remove(observer); + } + + /** @see Observer#onChanged(ItemHierarchy) */ + public void notifyChanged() { + for (Observer observer : observers) { + observer.onChanged(this); } + } - public int getViewId() { - return getId(); + /** @see Observer#onItemRangeChanged(ItemHierarchy, int, int) */ + public void notifyItemRangeChanged(int position, int itemCount) { + if (position < 0) { + Log.w(TAG, "notifyItemRangeChanged: Invalid position=" + position); + return; + } + if (itemCount < 0) { + Log.w(TAG, "notifyItemRangeChanged: Invalid itemCount=" + itemCount); + return; } - @Override - public void registerObserver(Observer observer) { - mObservers.add(observer); + for (Observer observer : observers) { + observer.onItemRangeChanged(this, position, itemCount); } + } - @Override - public void unregisterObserver(Observer observer) { - mObservers.remove(observer); + /** @see Observer#onItemRangeInserted(ItemHierarchy, int, int) */ + public void notifyItemRangeInserted(int position, int itemCount) { + if (position < 0) { + Log.w(TAG, "notifyItemRangeInserted: Invalid position=" + position); + return; + } + if (itemCount < 0) { + Log.w(TAG, "notifyItemRangeInserted: Invalid itemCount=" + itemCount); + return; } - /** - * @see Observer#onChanged(ItemHierarchy) - */ - public void notifyChanged() { - for (Observer observer : mObservers) { - observer.onChanged(this); - } + for (Observer observer : observers) { + observer.onItemRangeInserted(this, position, itemCount); } + } - /** - * @see Observer#onItemRangeChanged(ItemHierarchy, int, int) - */ - public void notifyItemRangeChanged(int position, int itemCount) { - if (position < 0) { - Log.w(TAG, "notifyItemRangeChanged: Invalid position=" + position); - return; - } - if (itemCount < 0) { - Log.w(TAG, "notifyItemRangeChanged: Invalid itemCount=" + itemCount); - return; - } - - for (Observer observer : mObservers) { - observer.onItemRangeChanged(this, position, itemCount); - } + /** @see Observer#onItemRangeMoved(ItemHierarchy, int, int, int) */ + public void notifyItemRangeMoved(int fromPosition, int toPosition, int itemCount) { + if (fromPosition < 0) { + Log.w(TAG, "notifyItemRangeMoved: Invalid fromPosition=" + fromPosition); + return; + } + if (toPosition < 0) { + Log.w(TAG, "notifyItemRangeMoved: Invalid toPosition=" + toPosition); + return; + } + if (itemCount < 0) { + Log.w(TAG, "notifyItemRangeMoved: Invalid itemCount=" + itemCount); + return; } - /** - * @see Observer#onItemRangeInserted(ItemHierarchy, int, int) - */ - public void notifyItemRangeInserted(int position, int itemCount) { - if (position < 0) { - Log.w(TAG, "notifyItemRangeInserted: Invalid position=" + position); - return; - } - if (itemCount < 0) { - Log.w(TAG, "notifyItemRangeInserted: Invalid itemCount=" + itemCount); - return; - } - - for (Observer observer : mObservers) { - observer.onItemRangeInserted(this, position, itemCount); - } + for (Observer observer : observers) { + observer.onItemRangeMoved(this, fromPosition, toPosition, itemCount); } + } - /** - * @see Observer#onItemRangeMoved(ItemHierarchy, int, int, int) - */ - public void notifyItemRangeMoved(int fromPosition, int toPosition, int itemCount) { - if (fromPosition < 0) { - Log.w(TAG, "notifyItemRangeMoved: Invalid fromPosition=" + fromPosition); - return; - } - if (toPosition < 0) { - Log.w(TAG, "notifyItemRangeMoved: Invalid toPosition=" + toPosition); - return; - } - if (itemCount < 0) { - Log.w(TAG, "notifyItemRangeMoved: Invalid itemCount=" + itemCount); - return; - } - - for (Observer observer : mObservers) { - observer.onItemRangeMoved(this, fromPosition, toPosition, itemCount); - } + /** @see Observer#onItemRangeRemoved(ItemHierarchy, int, int) */ + public void notifyItemRangeRemoved(int position, int itemCount) { + if (position < 0) { + Log.w(TAG, "notifyItemRangeInserted: Invalid position=" + position); + return; + } + if (itemCount < 0) { + Log.w(TAG, "notifyItemRangeInserted: Invalid itemCount=" + itemCount); + return; } - /** - * @see Observer#onItemRangeRemoved(ItemHierarchy, int, int) - */ - public void notifyItemRangeRemoved(int position, int itemCount) { - if (position < 0) { - Log.w(TAG, "notifyItemRangeInserted: Invalid position=" + position); - return; - } - if (itemCount < 0) { - Log.w(TAG, "notifyItemRangeInserted: Invalid itemCount=" + itemCount); - return; - } - - for (Observer observer : mObservers) { - observer.onItemRangeRemoved(this, position, itemCount); - } + for (Observer observer : observers) { + observer.onItemRangeRemoved(this, position, itemCount); } + } } diff --git a/library/main/src/com/android/setupwizardlib/items/ButtonBarItem.java b/library/main/src/com/android/setupwizardlib/items/ButtonBarItem.java index 06ce4ac..80b9453 100644 --- a/library/main/src/com/android/setupwizardlib/items/ButtonBarItem.java +++ b/library/main/src/com/android/setupwizardlib/items/ButtonBarItem.java @@ -21,16 +21,15 @@ import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; - import com.android.setupwizardlib.R; - import java.util.ArrayList; /** - * A list item with one or more buttons, declared as - * {@link com.android.setupwizardlib.items.ButtonItem}. + * A list item with one or more buttons, declared as {@link + * com.android.setupwizardlib.items.ButtonItem}. * * <p>Example usage: + * * <pre>{@code * <ButtonBarItem> * @@ -48,81 +47,81 @@ import java.util.ArrayList; */ public class ButtonBarItem extends AbstractItem implements ItemInflater.ItemParent { - private final ArrayList<ButtonItem> mButtons = new ArrayList<>(); - private boolean mVisible = true; - - public ButtonBarItem() { - super(); - } - - public ButtonBarItem(Context context, AttributeSet attrs) { - super(context, attrs); - } - - @Override - public int getCount() { - return isVisible() ? 1 : 0; - } - - @Override - public boolean isEnabled() { - // The children buttons are enabled and clickable, but the item itself is not - return false; + private final ArrayList<ButtonItem> buttons = new ArrayList<>(); + private boolean visible = true; + + public ButtonBarItem() { + super(); + } + + public ButtonBarItem(Context context, AttributeSet attrs) { + super(context, attrs); + } + + @Override + public int getCount() { + return isVisible() ? 1 : 0; + } + + @Override + public boolean isEnabled() { + // The children buttons are enabled and clickable, but the item itself is not + return false; + } + + @Override + public int getLayoutResource() { + return R.layout.suw_items_button_bar; + } + + public void setVisible(boolean visible) { + this.visible = visible; + } + + public boolean isVisible() { + return visible; + } + + @Override + public int getViewId() { + return getId(); + } + + @Override + public void onBindView(View view) { + // Note: The efficiency could be improved by trying to recycle the buttons created by + // ButtonItem + final LinearLayout layout = (LinearLayout) view; + layout.removeAllViews(); + + for (ButtonItem buttonItem : buttons) { + Button button = buttonItem.createButton(layout); + layout.addView(button); } - @Override - public int getLayoutResource() { - return R.layout.suw_items_button_bar; - } - - public void setVisible(boolean visible) { - mVisible = visible; - } - - public boolean isVisible() { - return mVisible; - } + view.setId(getViewId()); + } - @Override - public int getViewId() { - return getId(); + @Override + public void addChild(ItemHierarchy child) { + if (child instanceof ButtonItem) { + buttons.add((ButtonItem) child); + } else { + throw new UnsupportedOperationException("Cannot add non-button item to Button Bar"); } + } - @Override - public void onBindView(View view) { - // Note: The efficiency could be improved by trying to recycle the buttons created by - // ButtonItem - final LinearLayout layout = (LinearLayout) view; - layout.removeAllViews(); - - for (ButtonItem buttonItem : mButtons) { - Button button = buttonItem.createButton(layout); - layout.addView(button); - } - - view.setId(getViewId()); + @Override + public ItemHierarchy findItemById(int id) { + if (getId() == id) { + return this; } - - @Override - public void addChild(ItemHierarchy child) { - if (child instanceof ButtonItem) { - mButtons.add((ButtonItem) child); - } else { - throw new UnsupportedOperationException("Cannot add non-button item to Button Bar"); - } - } - - @Override - public ItemHierarchy findItemById(int id) { - if (getId() == id) { - return this; - } - for (ButtonItem button : mButtons) { - final ItemHierarchy item = button.findItemById(id); - if (item != null) { - return item; - } - } - return null; + for (ButtonItem button : buttons) { + final ItemHierarchy item = button.findItemById(id); + if (item != null) { + return item; + } } + return null; + } } diff --git a/library/main/src/com/android/setupwizardlib/items/ButtonItem.java b/library/main/src/com/android/setupwizardlib/items/ButtonItem.java index 07802ae..b398f4d 100644 --- a/library/main/src/com/android/setupwizardlib/items/ButtonItem.java +++ b/library/main/src/com/android/setupwizardlib/items/ButtonItem.java @@ -25,7 +25,6 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; - import com.android.setupwizardlib.R; /** @@ -34,128 +33,123 @@ import com.android.setupwizardlib.R; */ public class ButtonItem extends AbstractItem implements View.OnClickListener { - public interface OnClickListener { - void onClick(ButtonItem item); - } - - private boolean mEnabled = true; - private CharSequence mText; - private int mTheme = R.style.SuwButtonItem; - private OnClickListener mListener; - - private Button mButton; - - public ButtonItem() { - super(); - } - - public ButtonItem(Context context, AttributeSet attrs) { - super(context, attrs); - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SuwButtonItem); - mEnabled = a.getBoolean(R.styleable.SuwButtonItem_android_enabled, true); - mText = a.getText(R.styleable.SuwButtonItem_android_text); - mTheme = a.getResourceId(R.styleable.SuwButtonItem_android_theme, R.style.SuwButtonItem); - a.recycle(); - } - - public void setOnClickListener(OnClickListener listener) { - mListener = listener; - } - - public void setText(CharSequence text) { - mText = text; - } - - public CharSequence getText() { - return mText; - } - - /** - * The theme to use for this button. This can be used to create button of a particular style - * (e.g. a colored or borderless button). Typically {@code android:buttonStyle} will be set in - * the theme to change the style applied by the button. - * - * @param theme Resource ID of the theme - */ - public void setTheme(int theme) { - mTheme = theme; - mButton = null; - } - - /** - * @return Resource ID of the theme used by this button. - */ - public int getTheme() { - return mTheme; - } - - public void setEnabled(boolean enabled) { - mEnabled = enabled; - } - - @Override - public int getCount() { - return 0; - } - - @Override - public boolean isEnabled() { - return mEnabled; - } - - @Override - public int getLayoutResource() { - return 0; - } - - /** - * Do not use this since ButtonItem is not directly part of a list. - */ - @Override - public final void onBindView(View view) { - throw new UnsupportedOperationException("Cannot bind to ButtonItem's view"); - } - - /** - * Create a button according to this button item. - * - * @param parent The parent of the button, used to retrieve the theme and context for this - * button. - * @return A button that can be added to the parent. - */ - protected Button createButton(ViewGroup parent) { - if (mButton == null) { - Context context = parent.getContext(); - if (mTheme != 0) { - context = new ContextThemeWrapper(context, mTheme); - } - mButton = createButton(context); - mButton.setOnClickListener(this); - } else { - if (mButton.getParent() instanceof ViewGroup) { - // A view cannot be added to a different parent if one already exists. Remove this - // button from its parent before returning. - ((ViewGroup) mButton.getParent()).removeView(mButton); - } - } - mButton.setEnabled(mEnabled); - mButton.setText(mText); - mButton.setId(getViewId()); - return mButton; - } - - @Override - public void onClick(View v) { - if (mListener != null) { - mListener.onClick(this); - } - } - - @SuppressLint("InflateParams") // This is used similar to Button(Context), so it's OK to not - // specify the parent. - private Button createButton(Context context) { - // Inflate a single button from XML, so that when using support lib, it will take advantage - // of the injected layout inflater and give us AppCompatButton instead. - return (Button) LayoutInflater.from(context).inflate(R.layout.suw_button, null, false); - } + public interface OnClickListener { + void onClick(ButtonItem item); + } + + private boolean enabled = true; + private CharSequence text; + private int theme = R.style.SuwButtonItem; + private OnClickListener listener; + + private Button button; + + public ButtonItem() { + super(); + } + + public ButtonItem(Context context, AttributeSet attrs) { + super(context, attrs); + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SuwButtonItem); + enabled = a.getBoolean(R.styleable.SuwButtonItem_android_enabled, true); + text = a.getText(R.styleable.SuwButtonItem_android_text); + theme = a.getResourceId(R.styleable.SuwButtonItem_android_theme, R.style.SuwButtonItem); + a.recycle(); + } + + public void setOnClickListener(OnClickListener listener) { + this.listener = listener; + } + + public void setText(CharSequence text) { + this.text = text; + } + + public CharSequence getText() { + return text; + } + + /** + * The theme to use for this button. This can be used to create button of a particular style (e.g. + * a colored or borderless button). Typically {@code android:buttonStyle} will be set in the theme + * to change the style applied by the button. + * + * @param theme Resource ID of the theme + */ + public void setTheme(int theme) { + this.theme = theme; + button = null; + } + + /** @return Resource ID of the theme used by this button. */ + public int getTheme() { + return theme; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + @Override + public int getCount() { + return 0; + } + + @Override + public boolean isEnabled() { + return enabled; + } + + @Override + public int getLayoutResource() { + return 0; + } + + /** Do not use this since ButtonItem is not directly part of a list. */ + @Override + public final void onBindView(View view) { + throw new UnsupportedOperationException("Cannot bind to ButtonItem's view"); + } + + /** + * Create a button according to this button item. + * + * @param parent The parent of the button, used to retrieve the theme and context for this button. + * @return A button that can be added to the parent. + */ + protected Button createButton(ViewGroup parent) { + if (button == null) { + Context context = parent.getContext(); + if (theme != 0) { + context = new ContextThemeWrapper(context, theme); + } + button = createButton(context); + button.setOnClickListener(this); + } else { + if (button.getParent() instanceof ViewGroup) { + // A view cannot be added to a different parent if one already exists. Remove this + // button from its parent before returning. + ((ViewGroup) button.getParent()).removeView(button); + } + } + button.setEnabled(enabled); + button.setText(text); + button.setId(getViewId()); + return button; + } + + @SuppressLint("InflateParams") // This is used similar to Button(Context), so it's OK to not + // specify the parent. + private Button createButton(Context context) { + // Inflate a single button from XML, so that when using support lib, it will take advantage + // of the injected layout inflater and give us AppCompatButton instead. + return (Button) LayoutInflater.from(context).inflate(R.layout.suw_button, null, false); + } + + @Override + public void onClick(View v) { + if (listener != null) { + listener.onClick(this); + } + } } diff --git a/library/main/src/com/android/setupwizardlib/items/IItem.java b/library/main/src/com/android/setupwizardlib/items/IItem.java index 26391dc..cd29ec2 100644 --- a/library/main/src/com/android/setupwizardlib/items/IItem.java +++ b/library/main/src/com/android/setupwizardlib/items/IItem.java @@ -18,31 +18,27 @@ package com.android.setupwizardlib.items; import android.view.View; -/** - * Representation of an item in an {@link ItemHierarchy}. - */ +/** Representation of an item in an {@link ItemHierarchy}. */ public interface IItem { - /** - * Get the Android resource ID for locating the layout for this item. - * - * @return Resource ID for the layout of this item. This layout will be used to inflate the View - * passed to {@link #onBindView(android.view.View)}. - */ - int getLayoutResource(); + /** + * Get the Android resource ID for locating the layout for this item. + * + * @return Resource ID for the layout of this item. This layout will be used to inflate the View + * passed to {@link #onBindView(android.view.View)}. + */ + int getLayoutResource(); - /** - * Called by items framework to display the data specified by this item. This method should - * update {@code view} to reflect its data. - * - * @param view A view inflated from {@link #getLayoutResource()}, which should be updated to - * display data from this item. This view may be recycled from other items with the - * same layout resource. - */ - void onBindView(View view); + /** + * Called by items framework to display the data specified by this item. This method should update + * {@code view} to reflect its data. + * + * @param view A view inflated from {@link #getLayoutResource()}, which should be updated to + * display data from this item. This view may be recycled from other items with the same + * layout resource. + */ + void onBindView(View view); - /** - * @return True if this item is enabled. - */ - boolean isEnabled(); + /** @return True if this item is enabled. */ + boolean isEnabled(); } diff --git a/library/main/src/com/android/setupwizardlib/items/Item.java b/library/main/src/com/android/setupwizardlib/items/Item.java index fc8823e..c0d49d3 100644 --- a/library/main/src/com/android/setupwizardlib/items/Item.java +++ b/library/main/src/com/android/setupwizardlib/items/Item.java @@ -23,7 +23,6 @@ import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.TextView; - import com.android.setupwizardlib.R; /** @@ -32,146 +31,145 @@ import com.android.setupwizardlib.R; */ public class Item extends AbstractItem { - private boolean mEnabled = true; - private Drawable mIcon; - private int mLayoutRes; - private CharSequence mSummary; - private CharSequence mTitle; - private boolean mVisible = true; - - public Item() { - super(); - mLayoutRes = getDefaultLayoutResource(); - } - - public Item(Context context, AttributeSet attrs) { - super(context, attrs); - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SuwItem); - mEnabled = a.getBoolean(R.styleable.SuwItem_android_enabled, true); - mIcon = a.getDrawable(R.styleable.SuwItem_android_icon); - mTitle = a.getText(R.styleable.SuwItem_android_title); - mSummary = a.getText(R.styleable.SuwItem_android_summary); - mLayoutRes = a.getResourceId(R.styleable.SuwItem_android_layout, - getDefaultLayoutResource()); - mVisible = a.getBoolean(R.styleable.SuwItem_android_visible, true); - a.recycle(); - } - - protected int getDefaultLayoutResource() { - return R.layout.suw_items_default; - } - - public void setEnabled(boolean enabled) { - mEnabled = enabled; - notifyItemChanged(); - } - - @Override - public int getCount() { - return isVisible() ? 1 : 0; - } - - @Override - public boolean isEnabled() { - return mEnabled; - } - - public void setIcon(Drawable icon) { - mIcon = icon; - notifyItemChanged(); - } - - public Drawable getIcon() { - return mIcon; - } - - public void setLayoutResource(int layoutResource) { - mLayoutRes = layoutResource; - notifyItemChanged(); - } - - @Override - public int getLayoutResource() { - return mLayoutRes; - } - - public void setSummary(CharSequence summary) { - mSummary = summary; - notifyItemChanged(); - } - - public CharSequence getSummary() { - return mSummary; - } - - public void setTitle(CharSequence title) { - mTitle = title; - notifyItemChanged(); - } - - public CharSequence getTitle() { - return mTitle; - } - - public void setVisible(boolean visible) { - if (mVisible == visible) { - return; - } - mVisible = visible; - if (!visible) { - notifyItemRangeRemoved(0, 1); - } else { - notifyItemRangeInserted(0, 1); - } - } - - public boolean isVisible() { - return mVisible; - } - - @Override - public int getViewId() { - return getId(); - } - - @Override - public void onBindView(View view) { - TextView label = (TextView) view.findViewById(R.id.suw_items_title); - label.setText(getTitle()); - - TextView summaryView = (TextView) view.findViewById(R.id.suw_items_summary); - CharSequence summary = getSummary(); - if (summary != null && summary.length() > 0) { - summaryView.setText(summary); - summaryView.setVisibility(View.VISIBLE); - } else { - summaryView.setVisibility(View.GONE); - } - - final View iconContainer = view.findViewById(R.id.suw_items_icon_container); - final Drawable icon = getIcon(); - if (icon != null) { - final ImageView iconView = (ImageView) view.findViewById(R.id.suw_items_icon); - // Set the image drawable to null before setting the state and level to avoid affecting - // any recycled drawable in the ImageView - iconView.setImageDrawable(null); - onMergeIconStateAndLevels(iconView, icon); - iconView.setImageDrawable(icon); - iconContainer.setVisibility(View.VISIBLE); - } else { - iconContainer.setVisibility(View.GONE); - } - - view.setId(getViewId()); - } - - /** - * Copies state and level information from {@link #getIcon()} to the currently bound view's - * ImageView. Subclasses can override this method to change whats being copied from the icon - * to the ImageView. - */ - protected void onMergeIconStateAndLevels(ImageView iconView, Drawable icon) { - iconView.setImageState(icon.getState(), false /* merge */); - iconView.setImageLevel(icon.getLevel()); - } + private boolean enabled = true; + private Drawable icon; + private int layoutRes; + private CharSequence summary; + private CharSequence title; + private boolean visible = true; + + public Item() { + super(); + layoutRes = getDefaultLayoutResource(); + } + + public Item(Context context, AttributeSet attrs) { + super(context, attrs); + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SuwItem); + enabled = a.getBoolean(R.styleable.SuwItem_android_enabled, true); + icon = a.getDrawable(R.styleable.SuwItem_android_icon); + title = a.getText(R.styleable.SuwItem_android_title); + summary = a.getText(R.styleable.SuwItem_android_summary); + layoutRes = a.getResourceId(R.styleable.SuwItem_android_layout, getDefaultLayoutResource()); + visible = a.getBoolean(R.styleable.SuwItem_android_visible, true); + a.recycle(); + } + + protected int getDefaultLayoutResource() { + return R.layout.suw_items_default; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + notifyItemChanged(); + } + + @Override + public int getCount() { + return isVisible() ? 1 : 0; + } + + @Override + public boolean isEnabled() { + return enabled; + } + + public void setIcon(Drawable icon) { + this.icon = icon; + notifyItemChanged(); + } + + public Drawable getIcon() { + return icon; + } + + public void setLayoutResource(int layoutResource) { + layoutRes = layoutResource; + notifyItemChanged(); + } + + @Override + public int getLayoutResource() { + return layoutRes; + } + + public void setSummary(CharSequence summary) { + this.summary = summary; + notifyItemChanged(); + } + + public CharSequence getSummary() { + return summary; + } + + public void setTitle(CharSequence title) { + this.title = title; + notifyItemChanged(); + } + + public CharSequence getTitle() { + return title; + } + + public void setVisible(boolean visible) { + if (this.visible == visible) { + return; + } + this.visible = visible; + if (!visible) { + notifyItemRangeRemoved(0, 1); + } else { + notifyItemRangeInserted(0, 1); + } + } + + public boolean isVisible() { + return visible; + } + + @Override + public int getViewId() { + return getId(); + } + + @Override + public void onBindView(View view) { + TextView label = (TextView) view.findViewById(R.id.suw_items_title); + label.setText(getTitle()); + + TextView summaryView = (TextView) view.findViewById(R.id.suw_items_summary); + CharSequence summary = getSummary(); + if (summary != null && summary.length() > 0) { + summaryView.setText(summary); + summaryView.setVisibility(View.VISIBLE); + } else { + summaryView.setVisibility(View.GONE); + } + + final View iconContainer = view.findViewById(R.id.suw_items_icon_container); + final Drawable icon = getIcon(); + if (icon != null) { + final ImageView iconView = (ImageView) view.findViewById(R.id.suw_items_icon); + // Set the image drawable to null before setting the state and level to avoid affecting + // any recycled drawable in the ImageView + iconView.setImageDrawable(null); + onMergeIconStateAndLevels(iconView, icon); + iconView.setImageDrawable(icon); + iconContainer.setVisibility(View.VISIBLE); + } else { + iconContainer.setVisibility(View.GONE); + } + + view.setId(getViewId()); + } + + /** + * Copies state and level information from {@link #getIcon()} to the currently bound view's + * ImageView. Subclasses can override this method to change whats being copied from the icon to + * the ImageView. + */ + protected void onMergeIconStateAndLevels(ImageView iconView, Drawable icon) { + iconView.setImageState(icon.getState(), false /* merge */); + iconView.setImageLevel(icon.getLevel()); + } } diff --git a/library/main/src/com/android/setupwizardlib/items/ItemAdapter.java b/library/main/src/com/android/setupwizardlib/items/ItemAdapter.java index 53285e7..851736c 100644 --- a/library/main/src/com/android/setupwizardlib/items/ItemAdapter.java +++ b/library/main/src/com/android/setupwizardlib/items/ItemAdapter.java @@ -23,130 +23,130 @@ import android.view.ViewGroup; import android.widget.BaseAdapter; /** - * An adapter typically used with ListView to display an - * {@link com.android.setupwizardlib.items.ItemHierarchy}. The item hierarchy used to create this - * adapter can be inflated by {@link ItemInflater} from XML. + * An adapter typically used with ListView to display an {@link + * com.android.setupwizardlib.items.ItemHierarchy}. The item hierarchy used to create this adapter + * can be inflated by {@link ItemInflater} from XML. */ public class ItemAdapter extends BaseAdapter implements ItemHierarchy.Observer { - private final ItemHierarchy mItemHierarchy; - private ViewTypes mViewTypes = new ViewTypes(); - - public ItemAdapter(ItemHierarchy hierarchy) { - mItemHierarchy = hierarchy; - mItemHierarchy.registerObserver(this); - refreshViewTypes(); - } - - @Override - public int getCount() { - return mItemHierarchy.getCount(); - } - - @Override - public IItem getItem(int position) { - return mItemHierarchy.getItemAt(position); - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public int getItemViewType(int position) { - IItem item = getItem(position); - int layoutRes = item.getLayoutResource(); - return mViewTypes.get(layoutRes); - } - - @Override - public int getViewTypeCount() { - return mViewTypes.size(); - } - - private void refreshViewTypes() { - for (int i = 0; i < getCount(); i++) { - IItem item = getItem(i); - mViewTypes.add(item.getLayoutResource()); - } - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - IItem item = getItem(position); - if (convertView == null) { - LayoutInflater inflater = LayoutInflater.from(parent.getContext()); - convertView = inflater.inflate(item.getLayoutResource(), parent, false); - } - item.onBindView(convertView); - return convertView; - } - - @Override - public void onChanged(ItemHierarchy hierarchy) { - refreshViewTypes(); - notifyDataSetChanged(); - } - - @Override - public void onItemRangeChanged(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { - onChanged(itemHierarchy); - } - - @Override - public void onItemRangeInserted(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { - onChanged(itemHierarchy); - } - - @Override - public void onItemRangeMoved(ItemHierarchy itemHierarchy, int fromPosition, int toPosition, - int itemCount) { - onChanged(itemHierarchy); - } - - @Override - public void onItemRangeRemoved(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { - onChanged(itemHierarchy); - } - - @Override - public boolean isEnabled(int position) { - return getItem(position).isEnabled(); - } - - public ItemHierarchy findItemById(int id) { - return mItemHierarchy.findItemById(id); - } - - public ItemHierarchy getRootItemHierarchy() { - return mItemHierarchy; - } - - /** - * A helper class to pack a sparse set of integers (e.g. resource IDs) to a contiguous list of - * integers (e.g. adapter positions), providing mapping to retrieve the original ID from a given - * position. This is used to pack the view types of the adapter into contiguous integers from - * a given layout resource. - */ - private static class ViewTypes { - private SparseIntArray mPositionMap = new SparseIntArray(); - private int nextPosition = 0; - - public int add(int id) { - if (mPositionMap.indexOfKey(id) < 0) { - mPositionMap.put(id, nextPosition); - nextPosition++; - } - return mPositionMap.get(id); - } - - public int size() { - return mPositionMap.size(); - } - - public int get(int id) { - return mPositionMap.get(id); - } - } + private final ItemHierarchy itemHierarchy; + private final ViewTypes viewTypes = new ViewTypes(); + + public ItemAdapter(ItemHierarchy hierarchy) { + itemHierarchy = hierarchy; + itemHierarchy.registerObserver(this); + refreshViewTypes(); + } + + @Override + public int getCount() { + return itemHierarchy.getCount(); + } + + @Override + public IItem getItem(int position) { + return itemHierarchy.getItemAt(position); + } + + @Override + public long getItemId(int position) { + return position; + } + + @Override + public int getItemViewType(int position) { + IItem item = getItem(position); + int layoutRes = item.getLayoutResource(); + return viewTypes.get(layoutRes); + } + + @Override + public int getViewTypeCount() { + return viewTypes.size(); + } + + private void refreshViewTypes() { + for (int i = 0; i < getCount(); i++) { + IItem item = getItem(i); + viewTypes.add(item.getLayoutResource()); + } + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + IItem item = getItem(position); + if (convertView == null) { + LayoutInflater inflater = LayoutInflater.from(parent.getContext()); + convertView = inflater.inflate(item.getLayoutResource(), parent, false); + } + item.onBindView(convertView); + return convertView; + } + + @Override + public void onChanged(ItemHierarchy hierarchy) { + refreshViewTypes(); + notifyDataSetChanged(); + } + + @Override + public void onItemRangeChanged(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { + onChanged(itemHierarchy); + } + + @Override + public void onItemRangeInserted(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { + onChanged(itemHierarchy); + } + + @Override + public void onItemRangeMoved( + ItemHierarchy itemHierarchy, int fromPosition, int toPosition, int itemCount) { + onChanged(itemHierarchy); + } + + @Override + public void onItemRangeRemoved(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { + onChanged(itemHierarchy); + } + + @Override + public boolean isEnabled(int position) { + return getItem(position).isEnabled(); + } + + public ItemHierarchy findItemById(int id) { + return itemHierarchy.findItemById(id); + } + + public ItemHierarchy getRootItemHierarchy() { + return itemHierarchy; + } + + /** + * A helper class to pack a sparse set of integers (e.g. resource IDs) to a contiguous list of + * integers (e.g. adapter positions), providing mapping to retrieve the original ID from a given + * position. This is used to pack the view types of the adapter into contiguous integers from a + * given layout resource. + */ + private static class ViewTypes { + private final SparseIntArray positionMap = new SparseIntArray(); + private int nextPosition = 0; + + public int add(int id) { + if (positionMap.indexOfKey(id) < 0) { + positionMap.put(id, nextPosition); + nextPosition++; + } + return positionMap.get(id); + } + + public int size() { + return positionMap.size(); + } + + public int get(int id) { + return positionMap.get(id); + } + } } diff --git a/library/main/src/com/android/setupwizardlib/items/ItemGroup.java b/library/main/src/com/android/setupwizardlib/items/ItemGroup.java index 97b3199..246469f 100644 --- a/library/main/src/com/android/setupwizardlib/items/ItemGroup.java +++ b/library/main/src/com/android/setupwizardlib/items/ItemGroup.java @@ -20,301 +20,288 @@ import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.util.SparseIntArray; - import java.util.ArrayList; import java.util.List; -public class ItemGroup extends AbstractItemHierarchy implements ItemInflater.ItemParent, - ItemHierarchy.Observer { - - /* static section */ - - private static final String TAG = "ItemGroup"; - - /** - * Binary search for the closest value that's smaller than or equal to {@code value}, and - * return the corresponding key. - */ - private static int binarySearch(SparseIntArray array, int value) { - final int size = array.size(); - int lo = 0; - int hi = size - 1; - - while (lo <= hi) { - final int mid = (lo + hi) >>> 1; - final int midVal = array.valueAt(mid); - - if (midVal < value) { - lo = mid + 1; - } else if (midVal > value) { - hi = mid - 1; - } else { - return array.keyAt(mid); // value found - } - } - // Value not found. Return the last item before our search range, which is the closest - // value smaller than the value we are looking for. - return array.keyAt(lo - 1); +public class ItemGroup extends AbstractItemHierarchy + implements ItemInflater.ItemParent, ItemHierarchy.Observer { + + /* static section */ + + private static final String TAG = "ItemGroup"; + + /** + * Binary search for the closest value that's smaller than or equal to {@code value}, and return + * the corresponding key. + */ + private static int binarySearch(SparseIntArray array, int value) { + final int size = array.size(); + int lo = 0; + int hi = size - 1; + + while (lo <= hi) { + final int mid = (lo + hi) >>> 1; + final int midVal = array.valueAt(mid); + + if (midVal < value) { + lo = mid + 1; + } else if (midVal > value) { + hi = mid - 1; + } else { + return array.keyAt(mid); // value found + } } - - /** - * Same as {@link List#indexOf(Object)}, but using identity comparison rather than - * {@link Object#equals(Object)}. - */ - private static <T> int identityIndexOf(List<T> list, T object) { - final int count = list.size(); - for (int i = 0; i < count; i++) { - if (list.get(i) == object) { - return i; - } - } - return -1; + // Value not found. Return the last item before our search range, which is the closest + // value smaller than the value we are looking for. + return array.keyAt(lo - 1); + } + + /** + * Same as {@link List#indexOf(Object)}, but using identity comparison rather than {@link + * Object#equals(Object)}. + */ + private static <T> int identityIndexOf(List<T> list, T object) { + final int count = list.size(); + for (int i = 0; i < count; i++) { + if (list.get(i) == object) { + return i; + } } - - /* non-static section */ - - private List<ItemHierarchy> mChildren = new ArrayList<>(); - - /** - * A mapping from the index of an item hierarchy in mChildren, to the first position in which - * the corresponding child hierarchy represents. For example: - * - * ItemHierarchy Item Item Position - * Index - * - * 0 [ Wi-Fi AP 1 ] 0 - * | Wi-Fi AP 2 | 1 - * | Wi-Fi AP 3 | 2 - * | Wi-Fi AP 4 | 3 - * [ Wi-Fi AP 5 ] 4 - * - * 1 [ <Empty Item Hierarchy> ] - * - * 2 [ Use cellular data ] 5 - * - * 3 [ Don't connect ] 6 - * - * For this example of Wi-Fi screen, the following mapping will be produced: - * [ 0 -> 0 | 2 -> 5 | 3 -> 6 ] - * - * Also note how ItemHierarchy index 1 is not present in the map, because it is empty. - * - * ItemGroup uses this map to look for which ItemHierarchy an item at a given position belongs - * to. - */ - private SparseIntArray mHierarchyStart = new SparseIntArray(); - - private int mCount = 0; - private boolean mDirty = false; - - public ItemGroup() { - super(); + return -1; + } + + /* non-static section */ + + private final List<ItemHierarchy> children = new ArrayList<>(); + + /** + * A mapping from the index of an item hierarchy in children, to the first position in which the + * corresponding child hierarchy represents. For example: + * + * <p>ItemHierarchy Item Item Position Index + * + * <p>0 [ Wi-Fi AP 1 ] 0 | Wi-Fi AP 2 | 1 | Wi-Fi AP 3 | 2 | Wi-Fi AP 4 | 3 [ Wi-Fi AP 5 ] 4 + * + * <p>1 [ <Empty Item Hierarchy> ] + * + * <p>2 [ Use cellular data ] 5 + * + * <p>3 [ Don't connect ] 6 + * + * <p>For this example of Wi-Fi screen, the following mapping will be produced: [ 0 -> 0 | 2 -> 5 + * | 3 -> 6 ] + * + * <p>Also note how ItemHierarchy index 1 is not present in the map, because it is empty. + * + * <p>ItemGroup uses this map to look for which ItemHierarchy an item at a given position belongs + * to. + */ + private final SparseIntArray hierarchyStart = new SparseIntArray(); + + private int count = 0; + private boolean dirty = false; + + public ItemGroup() { + super(); + } + + public ItemGroup(Context context, AttributeSet attrs) { + // Constructor for XML inflation + super(context, attrs); + } + + /** Add a child hierarchy to this item group. */ + @Override + public void addChild(ItemHierarchy child) { + dirty = true; + children.add(child); + child.registerObserver(this); + + final int count = child.getCount(); + if (count > 0) { + notifyItemRangeInserted(getChildPosition(child), count); } - - public ItemGroup(Context context, AttributeSet attrs) { - // Constructor for XML inflation - super(context, attrs); - } - - /** - * Add a child hierarchy to this item group. - */ - @Override - public void addChild(ItemHierarchy child) { - mDirty = true; - mChildren.add(child); - child.registerObserver(this); - - final int count = child.getCount(); - if (count > 0) { - notifyItemRangeInserted(getChildPosition(child), count); - } + } + + /** + * Remove a previously added child from this item group. + * + * @return True if there is a match for the child and it is removed. False if the child could not + * be found in our list of child hierarchies. + */ + public boolean removeChild(ItemHierarchy child) { + final int childIndex = identityIndexOf(children, child); + final int childPosition = getChildPosition(childIndex); + dirty = true; + if (childIndex != -1) { + final int childCount = child.getCount(); + children.remove(childIndex); + child.unregisterObserver(this); + if (childCount > 0) { + notifyItemRangeRemoved(childPosition, childCount); + } + return true; } + return false; + } - /** - * Remove a previously added child from this item group. - * - * @return True if there is a match for the child and it is removed. False if the child could - * not be found in our list of child hierarchies. - */ - public boolean removeChild(ItemHierarchy child) { - final int childIndex = identityIndexOf(mChildren, child); - final int childPosition = getChildPosition(childIndex); - mDirty = true; - if (childIndex != -1) { - final int childCount = child.getCount(); - mChildren.remove(childIndex); - child.unregisterObserver(this); - if (childCount > 0) { - notifyItemRangeRemoved(childPosition, childCount); - } - return true; - } - return false; + /** Remove all children from this hierarchy. */ + public void clear() { + if (children.isEmpty()) { + return; } - /** - * Remove all children from this hierarchy. - */ - public void clear() { - if (mChildren.size() == 0) { - return; - } - - final int numRemoved = getCount(); + final int numRemoved = getCount(); - for (ItemHierarchy item : mChildren) { - item.unregisterObserver(this); - } - mDirty = true; - mChildren.clear(); - notifyItemRangeRemoved(0, numRemoved); + for (ItemHierarchy item : children) { + item.unregisterObserver(this); } - - @Override - public int getCount() { - updateDataIfNeeded(); - return mCount; + dirty = true; + children.clear(); + notifyItemRangeRemoved(0, numRemoved); + } + + @Override + public int getCount() { + updateDataIfNeeded(); + return count; + } + + @Override + public IItem getItemAt(int position) { + int itemIndex = getItemIndex(position); + ItemHierarchy item = children.get(itemIndex); + int subpos = position - hierarchyStart.get(itemIndex); + return item.getItemAt(subpos); + } + + @Override + public void onChanged(ItemHierarchy hierarchy) { + // Need to set dirty, because our children may have gotten more items. + dirty = true; + notifyChanged(); + } + + /** + * @return The "Item Position" of the given child, or -1 if the child is not found. If the given + * child is empty, position of the next visible item is returned. + */ + private int getChildPosition(ItemHierarchy child) { + // Check the identity of the child rather than using .equals(), because here we want + // to find the index of the instance itself rather than something that equals to it. + return getChildPosition(identityIndexOf(children, child)); + } + + private int getChildPosition(int childIndex) { + updateDataIfNeeded(); + if (childIndex != -1) { + int childPos = -1; + int childCount = children.size(); + for (int i = childIndex; childPos < 0 && i < childCount; i++) { + // Find the position of the first visible child after childIndex. This is required + // when removing the last item from a nested ItemGroup. + childPos = hierarchyStart.get(i, -1); + } + if (childPos < 0) { + // If the last item in a group is being removed, there will be no visible item. + // In that case return the count instead, since that is where the item would have + // been if the child is not empty. + childPos = getCount(); + } + return childPos; } - - @Override - public IItem getItemAt(int position) { - int itemIndex = getItemIndex(position); - ItemHierarchy item = mChildren.get(itemIndex); - int subpos = position - mHierarchyStart.get(itemIndex); - return item.getItemAt(subpos); + return -1; + } + + @Override + public void onItemRangeChanged(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { + // No need to set dirty because onItemRangeChanged does not include any structural changes. + final int childPosition = getChildPosition(itemHierarchy); + if (childPosition >= 0) { + notifyItemRangeChanged(childPosition + positionStart, itemCount); + } else { + Log.e(TAG, "Unexpected child change " + itemHierarchy); } - - @Override - public void onChanged(ItemHierarchy hierarchy) { - // Need to set dirty, because our children may have gotten more items. - mDirty = true; - notifyChanged(); + } + + @Override + public void onItemRangeInserted(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { + dirty = true; + final int childPosition = getChildPosition(itemHierarchy); + if (childPosition >= 0) { + notifyItemRangeInserted(childPosition + positionStart, itemCount); + } else { + Log.e(TAG, "Unexpected child insert " + itemHierarchy); } - - /** - * @return The "Item Position" of the given child, or -1 if the child is not found. If the given - * child is empty, position of the next visible item is returned. - */ - private int getChildPosition(ItemHierarchy child) { - // Check the identity of the child rather than using .equals(), because here we want - // to find the index of the instance itself rather than something that equals to it. - return getChildPosition(identityIndexOf(mChildren, child)); + } + + @Override + public void onItemRangeMoved( + ItemHierarchy itemHierarchy, int fromPosition, int toPosition, int itemCount) { + dirty = true; + final int childPosition = getChildPosition(itemHierarchy); + if (childPosition >= 0) { + notifyItemRangeMoved(childPosition + fromPosition, childPosition + toPosition, itemCount); + } else { + Log.e(TAG, "Unexpected child move " + itemHierarchy); } - - private int getChildPosition(int childIndex) { - updateDataIfNeeded(); - if (childIndex != -1) { - int childPos = -1; - int childCount = mChildren.size(); - for (int i = childIndex; childPos < 0 && i < childCount; i++) { - // Find the position of the first visible child after childIndex. This is required - // when removing the last item from a nested ItemGroup. - childPos = mHierarchyStart.get(i, -1); - } - if (childPos < 0) { - // If the last item in a group is being removed, there will be no visible item. - // In that case return the count instead, since that is where the item would have - // been if the child is not empty. - childPos = getCount(); - } - return childPos; - } - return -1; + } + + @Override + public void onItemRangeRemoved(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { + dirty = true; + final int childPosition = getChildPosition(itemHierarchy); + if (childPosition >= 0) { + notifyItemRangeRemoved(childPosition + positionStart, itemCount); + } else { + Log.e(TAG, "Unexpected child remove " + itemHierarchy); } + } - @Override - public void onItemRangeChanged(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { - // No need to set dirty because onItemRangeChanged does not include any structural changes. - final int childPosition = getChildPosition(itemHierarchy); - if (childPosition >= 0) { - notifyItemRangeChanged(childPosition + positionStart, itemCount); - } else { - Log.e(TAG, "Unexpected child change " + itemHierarchy); - } + @Override + public ItemHierarchy findItemById(int id) { + if (id == getId()) { + return this; } - - @Override - public void onItemRangeInserted(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { - mDirty = true; - final int childPosition = getChildPosition(itemHierarchy); - if (childPosition >= 0) { - notifyItemRangeInserted(childPosition + positionStart, itemCount); - } else { - Log.e(TAG, "Unexpected child insert " + itemHierarchy); - } + for (ItemHierarchy child : children) { + ItemHierarchy childFindItem = child.findItemById(id); + if (childFindItem != null) { + return childFindItem; + } } - - @Override - public void onItemRangeMoved(ItemHierarchy itemHierarchy, int fromPosition, int toPosition, - int itemCount) { - mDirty = true; - final int childPosition = getChildPosition(itemHierarchy); - if (childPosition >= 0) { - notifyItemRangeMoved(childPosition + fromPosition, childPosition + toPosition, - itemCount); - } else { - Log.e(TAG, "Unexpected child move " + itemHierarchy); + return null; + } + + /** If dirty, this method will recalculate the number of items and hierarchyStart. */ + private void updateDataIfNeeded() { + if (dirty) { + count = 0; + hierarchyStart.clear(); + for (int itemIndex = 0; itemIndex < children.size(); itemIndex++) { + ItemHierarchy item = children.get(itemIndex); + if (item.getCount() > 0) { + hierarchyStart.put(itemIndex, count); } + count += item.getCount(); + } + dirty = false; } - - @Override - public void onItemRangeRemoved(ItemHierarchy itemHierarchy, int positionStart, int itemCount) { - mDirty = true; - final int childPosition = getChildPosition(itemHierarchy); - if (childPosition >= 0) { - notifyItemRangeRemoved(childPosition + positionStart, itemCount); - } else { - Log.e(TAG, "Unexpected child remove " + itemHierarchy); - } + } + + /** + * Use binary search to locate the item hierarchy a position is contained in. + * + * @return Index of the item hierarchy which is responsible for the item at {@code position}. + */ + private int getItemIndex(int position) { + updateDataIfNeeded(); + if (position < 0 || position >= count) { + throw new IndexOutOfBoundsException("size=" + count + "; index=" + position); } - - @Override - public ItemHierarchy findItemById(int id) { - if (id == getId()) { - return this; - } - for (ItemHierarchy child : mChildren) { - ItemHierarchy childFindItem = child.findItemById(id); - if (childFindItem != null) { - return childFindItem; - } - } - return null; - } - - /** - * If dirty, this method will recalculate the number of items and mHierarchyStart. - */ - private void updateDataIfNeeded() { - if (mDirty) { - mCount = 0; - mHierarchyStart.clear(); - for (int itemIndex = 0; itemIndex < mChildren.size(); itemIndex++) { - ItemHierarchy item = mChildren.get(itemIndex); - if (item.getCount() > 0) { - mHierarchyStart.put(itemIndex, mCount); - } - mCount += item.getCount(); - } - mDirty = false; - } - } - - /** - * Use binary search to locate the item hierarchy a position is contained in. - * - * @return Index of the item hierarchy which is responsible for the item at {@code position}. - */ - private int getItemIndex(int position) { - updateDataIfNeeded(); - if (position < 0 || position >= mCount) { - throw new IndexOutOfBoundsException("size=" + mCount + "; index=" + position); - } - int result = binarySearch(mHierarchyStart, position); - if (result < 0) { - throw new IllegalStateException("Cannot have item start index < 0"); - } - return result; + int result = binarySearch(hierarchyStart, position); + if (result < 0) { + throw new IllegalStateException("Cannot have item start index < 0"); } + return result; + } } diff --git a/library/main/src/com/android/setupwizardlib/items/ItemHierarchy.java b/library/main/src/com/android/setupwizardlib/items/ItemHierarchy.java index 627b6f0..85e0870 100644 --- a/library/main/src/com/android/setupwizardlib/items/ItemHierarchy.java +++ b/library/main/src/com/android/setupwizardlib/items/ItemHierarchy.java @@ -20,82 +20,69 @@ package com.android.setupwizardlib.items; * Representation of zero or more items in a list. Each instance of ItemHierarchy should be capable * of being wrapped in ItemAdapter and be displayed. * - * For example, {@link com.android.setupwizardlib.items.Item} is a representation of a single item, - * typically with data provided from XML. {@link com.android.setupwizardlib.items.ItemGroup} + * <p>For example, {@link com.android.setupwizardlib.items.Item} is a representation of a single + * item, typically with data provided from XML. {@link com.android.setupwizardlib.items.ItemGroup} * represents a list of child item hierarchies it contains, but itself does not do any display. */ public interface ItemHierarchy { + /** + * Observer for any changes in this hierarchy. If anything updated that causes this hierarchy to + * show different content, this observer should be called. + */ + interface Observer { /** - * Observer for any changes in this hierarchy. If anything updated that causes this hierarchy to - * show different content, this observer should be called. + * Called when an underlying data update that can cause this hierarchy to show different content + * has occurred. + * + * <p>Note: This is a catch-all notification, but recycler view will have a harder time figuring + * out the animations for the change, and might even not animate the change at all. */ - interface Observer { - /** - * Called when an underlying data update that can cause this hierarchy to show different - * content has occurred. - * - * <p>Note: This is a catch-all notification, but recycler view will have a harder time - * figuring out the animations for the change, and might even not animate the change at all. - */ - void onChanged(ItemHierarchy itemHierarchy); + void onChanged(ItemHierarchy itemHierarchy); - /** - * Called when an underlying data update that can cause changes that are local to the given - * items. This method indicates that there are no structural changes like inserting or - * removing items. - */ - void onItemRangeChanged(ItemHierarchy itemHierarchy, int positionStart, int itemCount); + /** + * Called when an underlying data update that can cause changes that are local to the given + * items. This method indicates that there are no structural changes like inserting or removing + * items. + */ + void onItemRangeChanged(ItemHierarchy itemHierarchy, int positionStart, int itemCount); - /** - * Called when items are inserted at the given position. - */ - void onItemRangeInserted(ItemHierarchy itemHierarchy, int positionStart, int itemCount); + /** Called when items are inserted at the given position. */ + void onItemRangeInserted(ItemHierarchy itemHierarchy, int positionStart, int itemCount); - /** - * Called when the given items are moved to a different position. - */ - void onItemRangeMoved(ItemHierarchy itemHierarchy, int fromPosition, int toPosition, - int itemCount); + /** Called when the given items are moved to a different position. */ + void onItemRangeMoved( + ItemHierarchy itemHierarchy, int fromPosition, int toPosition, int itemCount); - /** - * Called when the given items are removed from the item hierarchy. - */ - void onItemRangeRemoved(ItemHierarchy itemHierarchy, int positionStart, int itemCount); - } + /** Called when the given items are removed from the item hierarchy. */ + void onItemRangeRemoved(ItemHierarchy itemHierarchy, int positionStart, int itemCount); + } - /** - * Register an observer to observe changes for this item hierarchy. - */ - void registerObserver(Observer observer); + /** Register an observer to observe changes for this item hierarchy. */ + void registerObserver(Observer observer); - /** - * Unregister a previously registered observer. - */ - void unregisterObserver(Observer observer); + /** Unregister a previously registered observer. */ + void unregisterObserver(Observer observer); - /** - * @return the number of items this item hierarchy represent. - */ - int getCount(); + /** @return the number of items this item hierarchy represent. */ + int getCount(); - /** - * Get the item at position. - * - * @param position An integer from 0 to {@link #getCount()}}, which indicates the position in - * this item hierarchy to get the child item. - * @return A representation of the item at {@code position}. Must not be {@code null}. - */ - IItem getItemAt(int position); + /** + * Get the item at position. + * + * @param position An integer from 0 to {@link #getCount()}}, which indicates the position in this + * item hierarchy to get the child item. + * @return A representation of the item at {@code position}. Must not be {@code null}. + */ + IItem getItemAt(int position); - /** - * Find an item hierarchy within this hierarchy which has the given ID. Or null if no match is - * found. This hierarchy will be returned if our ID matches. Same restrictions for Android - * resource IDs apply to this ID. In fact, typically this ID is a resource ID generated from - * XML. - * - * @param id An ID to search for in this item hierarchy. - * @return An ItemHierarchy which matches the given ID. - */ - ItemHierarchy findItemById(int id); + /** + * Find an item hierarchy within this hierarchy which has the given ID. Or null if no match is + * found. This hierarchy will be returned if our ID matches. Same restrictions for Android + * resource IDs apply to this ID. In fact, typically this ID is a resource ID generated from XML. + * + * @param id An ID to search for in this item hierarchy. + * @return An ItemHierarchy which matches the given ID. + */ + ItemHierarchy findItemById(int id); } diff --git a/library/main/src/com/android/setupwizardlib/items/ItemInflater.java b/library/main/src/com/android/setupwizardlib/items/ItemInflater.java index 618d785..26cdbbd 100644 --- a/library/main/src/com/android/setupwizardlib/items/ItemInflater.java +++ b/library/main/src/com/android/setupwizardlib/items/ItemInflater.java @@ -18,26 +18,24 @@ package com.android.setupwizardlib.items; import android.content.Context; -/** - * Inflate {@link Item} hierarchies from XML files. - */ +/** Inflate {@link Item} hierarchies from XML files. */ public class ItemInflater extends ReflectionInflater<ItemHierarchy> { - public interface ItemParent { - void addChild(ItemHierarchy child); - } + public interface ItemParent { + void addChild(ItemHierarchy child); + } - public ItemInflater(Context context) { - super(context); - setDefaultPackage(Item.class.getPackage().getName() + "."); - } + public ItemInflater(Context context) { + super(context); + setDefaultPackage(Item.class.getPackage().getName() + "."); + } - @Override - protected void onAddChildItem(ItemHierarchy parent, ItemHierarchy child) { - if (parent instanceof ItemParent) { - ((ItemParent) parent).addChild(child); - } else { - throw new IllegalArgumentException("Cannot add child item to " + parent); - } + @Override + protected void onAddChildItem(ItemHierarchy parent, ItemHierarchy child) { + if (parent instanceof ItemParent) { + ((ItemParent) parent).addChild(child); + } else { + throw new IllegalArgumentException("Cannot add child item to " + parent); } + } } diff --git a/library/main/src/com/android/setupwizardlib/items/ReflectionInflater.java b/library/main/src/com/android/setupwizardlib/items/ReflectionInflater.java index 8ffa943..3382f56 100644 --- a/library/main/src/com/android/setupwizardlib/items/ReflectionInflater.java +++ b/library/main/src/com/android/setupwizardlib/items/ReflectionInflater.java @@ -17,12 +17,10 @@ package com.android.setupwizardlib.items; import android.content.Context; -import android.util.AttributeSet; -import android.view.InflateException; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; - +import android.util.AttributeSet; +import android.view.InflateException; import java.lang.reflect.Constructor; import java.util.HashMap; @@ -38,107 +36,104 @@ import java.util.HashMap; */ public abstract class ReflectionInflater<T> extends SimpleInflater<T> { - /* static section */ - - private static final Class<?>[] CONSTRUCTOR_SIGNATURE = - new Class<?>[] {Context.class, AttributeSet.class}; - - private static final HashMap<String, Constructor<?>> sConstructorMap = new HashMap<>(); - - /* non-static section */ - - // Array used to contain the constructor arguments (Context, AttributeSet), to avoid allocating - // a new array for creation of every item. - private final Object[] mTempConstructorArgs = new Object[2]; - - @Nullable - private String mDefaultPackage; - - @NonNull - private final Context mContext; - - /** - * Create a new inflater instance associated with a particular Context. - * - * @param context The context used to resolve resource IDs. This context is also passed to the - * constructor of the items created as the first argument. - */ - protected ReflectionInflater(@NonNull Context context) { - super(context.getResources()); - mContext = context; + /* static section */ + + private static final Class<?>[] CONSTRUCTOR_SIGNATURE = + new Class<?>[] {Context.class, AttributeSet.class}; + + private static final HashMap<String, Constructor<?>> constructorMap = new HashMap<>(); + + /* non-static section */ + + // Array used to contain the constructor arguments (Context, AttributeSet), to avoid allocating + // a new array for creation of every item. + private final Object[] tempConstructorArgs = new Object[2]; + + @Nullable private String defaultPackage; + + @NonNull private final Context context; + + /** + * Create a new inflater instance associated with a particular Context. + * + * @param context The context used to resolve resource IDs. This context is also passed to the + * constructor of the items created as the first argument. + */ + protected ReflectionInflater(@NonNull Context context) { + super(context.getResources()); + this.context = context; + } + + @NonNull + public Context getContext() { + return context; + } + + /** + * Instantiate the class by name. This attempts to instantiate class of the given {@code name} + * found in this inflater's ClassLoader. + * + * @param tagName The full name of the class to be instantiated. + * @param attrs The XML attributes supplied for this instance. + * @return The newly instantiated item. + */ + @NonNull + public final T createItem(String tagName, String prefix, AttributeSet attrs) { + String qualifiedName = tagName; + if (prefix != null && qualifiedName.indexOf('.') == -1) { + qualifiedName = prefix.concat(qualifiedName); } + @SuppressWarnings("unchecked") // qualifiedName should correspond to a subclass of T + Constructor<? extends T> constructor = + (Constructor<? extends T>) constructorMap.get(qualifiedName); - @NonNull - public Context getContext() { - return mContext; - } - - /** - * Instantiate the class by name. This attempts to instantiate class of the given {@code name} - * found in this inflater's ClassLoader. - * - * @param tagName The full name of the class to be instantiated. - * @param attrs The XML attributes supplied for this instance. - * - * @return The newly instantiated item. - */ - @NonNull - public final T createItem(String tagName, String prefix, AttributeSet attrs) { - String qualifiedName = tagName; - if (prefix != null && qualifiedName.indexOf('.') == -1) { - qualifiedName = prefix.concat(qualifiedName); - } + try { + if (constructor == null) { + // Class not found in the cache, see if it's real, and try to add it @SuppressWarnings("unchecked") // qualifiedName should correspond to a subclass of T - Constructor<? extends T> constructor = - (Constructor<? extends T>) sConstructorMap.get(qualifiedName); - - try { - if (constructor == null) { - // Class not found in the cache, see if it's real, and try to add it - @SuppressWarnings("unchecked") // qualifiedName should correspond to a subclass of T - Class<? extends T> clazz = - (Class<? extends T>) mContext.getClassLoader().loadClass(qualifiedName); - constructor = clazz.getConstructor(CONSTRUCTOR_SIGNATURE); - constructor.setAccessible(true); - sConstructorMap.put(tagName, constructor); - } - - mTempConstructorArgs[0] = mContext; - mTempConstructorArgs[1] = attrs; - final T item = constructor.newInstance(mTempConstructorArgs); - mTempConstructorArgs[0] = null; - mTempConstructorArgs[1] = null; - return item; - } catch (Exception e) { - throw new InflateException(attrs.getPositionDescription() - + ": Error inflating class " + qualifiedName, e); - } - } - - @Override - protected T onCreateItem(String tagName, AttributeSet attrs) { - return createItem(tagName, mDefaultPackage, attrs); - } - - /** - * Sets the default package that will be searched for classes to construct for tag names that - * have no explicit package. - * - * @param defaultPackage The default package. This will be prepended to the tag name, so it - * should end with a period. - */ - public void setDefaultPackage(@Nullable String defaultPackage) { - mDefaultPackage = defaultPackage; - } - - /** - * Returns the default package, or null if it is not set. - * - * @see #setDefaultPackage(String) - * @return The default package. - */ - @Nullable - public String getDefaultPackage() { - return mDefaultPackage; + Class<? extends T> clazz = + (Class<? extends T>) context.getClassLoader().loadClass(qualifiedName); + constructor = clazz.getConstructor(CONSTRUCTOR_SIGNATURE); + constructor.setAccessible(true); + constructorMap.put(tagName, constructor); + } + + tempConstructorArgs[0] = context; + tempConstructorArgs[1] = attrs; + final T item = constructor.newInstance(tempConstructorArgs); + tempConstructorArgs[0] = null; + tempConstructorArgs[1] = null; + return item; + } catch (Exception e) { + throw new InflateException( + attrs.getPositionDescription() + ": Error inflating class " + qualifiedName, e); } + } + + @Override + protected T onCreateItem(String tagName, AttributeSet attrs) { + return createItem(tagName, defaultPackage, attrs); + } + + /** + * Sets the default package that will be searched for classes to construct for tag names that have + * no explicit package. + * + * @param defaultPackage The default package. This will be prepended to the tag name, so it should + * end with a period. + */ + public void setDefaultPackage(@Nullable String defaultPackage) { + this.defaultPackage = defaultPackage; + } + + /** + * Returns the default package, or null if it is not set. + * + * @see #setDefaultPackage(String) + * @return The default package. + */ + @Nullable + public String getDefaultPackage() { + return defaultPackage; + } } diff --git a/library/main/src/com/android/setupwizardlib/items/SimpleInflater.java b/library/main/src/com/android/setupwizardlib/items/SimpleInflater.java index 0b12aca..767362c 100644 --- a/library/main/src/com/android/setupwizardlib/items/SimpleInflater.java +++ b/library/main/src/com/android/setupwizardlib/items/SimpleInflater.java @@ -18,18 +18,15 @@ package com.android.setupwizardlib.items; import android.content.res.Resources; import android.content.res.XmlResourceParser; +import androidx.annotation.NonNull; import android.util.AttributeSet; import android.util.Log; import android.util.Xml; import android.view.InflateException; - -import androidx.annotation.NonNull; - +import java.io.IOException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; -import java.io.IOException; - /** * A simple XML inflater, which takes care of moving the parser to the correct position. Subclasses * need to implement {@link #onCreateItem(String, AttributeSet)} to create an object representation @@ -40,154 +37,154 @@ import java.io.IOException; */ public abstract class SimpleInflater<T> { - private static final String TAG = "SimpleInflater"; - private static final boolean DEBUG = false; - - protected final Resources mResources; - - /** - * Create a new inflater instance associated with a particular Resources bundle. - * - * @param resources The Resources class used to resolve given resource IDs. - */ - protected SimpleInflater(@NonNull Resources resources) { - mResources = resources; + private static final String TAG = "SimpleInflater"; + private static final boolean DEBUG = false; + + protected final Resources mResources; + + /** + * Create a new inflater instance associated with a particular Resources bundle. + * + * @param resources The Resources class used to resolve given resource IDs. + */ + protected SimpleInflater(@NonNull Resources resources) { + mResources = resources; + } + + public Resources getResources() { + return mResources; + } + + /** + * Inflate a new hierarchy from the specified XML resource. Throws InflaterException if there is + * an error. + * + * @param resId ID for an XML resource to load (e.g. <code>R.xml.my_xml</code>) + * @return The root of the inflated hierarchy. + */ + public T inflate(int resId) { + XmlResourceParser parser = getResources().getXml(resId); + try { + return inflate(parser); + } finally { + parser.close(); } - - public Resources getResources() { - return mResources; - } - - /** - * Inflate a new hierarchy from the specified XML resource. Throws InflaterException if there is - * an error. - * - * @param resId ID for an XML resource to load (e.g. <code>R.xml.my_xml</code>) - * @return The root of the inflated hierarchy. - */ - public T inflate(int resId) { - XmlResourceParser parser = getResources().getXml(resId); - try { - return inflate(parser); - } finally { - parser.close(); - } - } - - /** - * Inflate a new hierarchy from the specified XML node. Throws InflaterException if there is an - * error. - * <p> - * <em><strong>Important</strong></em> For performance - * reasons, inflation relies heavily on pre-processing of XML files - * that is done at build time. Therefore, it is not currently possible to - * use inflater with an XmlPullParser over a plain XML file at runtime. - * - * @param parser XML dom node containing the description of the hierarchy. - * @return The root of the inflated hierarchy. - */ - public T inflate(XmlPullParser parser) { - final AttributeSet attrs = Xml.asAttributeSet(parser); - T createdItem; - - try { - // Look for the root node. - int type; - while ((type = parser.next()) != XmlPullParser.START_TAG - && type != XmlPullParser.END_DOCUMENT) { - // continue - } - - if (type != XmlPullParser.START_TAG) { - throw new InflateException(parser.getPositionDescription() - + ": No start tag found!"); - } - - createdItem = createItemFromTag(parser.getName(), attrs); - - rInflate(parser, createdItem, attrs); - } catch (XmlPullParserException e) { - throw new InflateException(e.getMessage(), e); - } catch (IOException e) { - throw new InflateException(parser.getPositionDescription() + ": " + e.getMessage(), e); - } - - return createdItem; + } + + /** + * Inflate a new hierarchy from the specified XML node. Throws InflaterException if there is an + * error. + * + * <p><em><strong>Important</strong></em> For performance reasons, inflation + * relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not + * currently possible to use inflater with an XmlPullParser over a plain XML file at runtime. + * + * @param parser XML dom node containing the description of the hierarchy. + * @return The root of the inflated hierarchy. + */ + public T inflate(XmlPullParser parser) { + final AttributeSet attrs = Xml.asAttributeSet(parser); + T createdItem; + + try { + // Look for the root node. + int type; + while ((type = parser.next()) != XmlPullParser.START_TAG + && type != XmlPullParser.END_DOCUMENT) { + // continue + } + + if (type != XmlPullParser.START_TAG) { + throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); + } + + createdItem = createItemFromTag(parser.getName(), attrs); + + rInflate(parser, createdItem, attrs); + } catch (XmlPullParserException e) { + throw new InflateException(e.getMessage(), e); + } catch (IOException e) { + throw new InflateException(parser.getPositionDescription() + ": " + e.getMessage(), e); } - /** - * This routine is responsible for creating the correct subclass of item - * given the xml element name. - * - * @param tagName The XML tag name for the item to be created. - * @param attrs An AttributeSet of attributes to apply to the item. - * @return The item created. - */ - protected abstract T onCreateItem(String tagName, AttributeSet attrs); - - private T createItemFromTag(String name, AttributeSet attrs) { - try { - T item = onCreateItem(name, attrs); - if (DEBUG) Log.v(TAG, item + " created for <" + name + ">"); - return item; - } catch (InflateException e) { - throw e; - } catch (Exception e) { - throw new InflateException(attrs.getPositionDescription() - + ": Error inflating class " + name, e); - } + return createdItem; + } + + /** + * This routine is responsible for creating the correct subclass of item given the xml element + * name. + * + * @param tagName The XML tag name for the item to be created. + * @param attrs An AttributeSet of attributes to apply to the item. + * @return The item created. + */ + protected abstract T onCreateItem(String tagName, AttributeSet attrs); + + private T createItemFromTag(String name, AttributeSet attrs) { + try { + T item = onCreateItem(name, attrs); + if (DEBUG) { + Log.v(TAG, item + " created for <" + name + ">"); + } + return item; + } catch (InflateException e) { + throw e; + } catch (Exception e) { + throw new InflateException( + attrs.getPositionDescription() + ": Error inflating class " + name, e); } + } - /** - * Recursive method used to descend down the xml hierarchy and instantiate - * items, instantiate their children, and then call onFinishInflate(). - */ - private void rInflate(XmlPullParser parser, T parent, final AttributeSet attrs) - throws XmlPullParserException, IOException { - final int depth = parser.getDepth(); - - int type; - while (((type = parser.next()) != XmlPullParser.END_TAG - || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { + /** + * Recursive method used to descend down the xml hierarchy and instantiate items, instantiate + * their children, and then call onFinishInflate(). + */ + private void rInflate(XmlPullParser parser, T parent, final AttributeSet attrs) + throws XmlPullParserException, IOException { + final int depth = parser.getDepth(); - if (type != XmlPullParser.START_TAG) { - continue; - } + int type; + while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) + && type != XmlPullParser.END_DOCUMENT) { - if (onInterceptCreateItem(parser, parent, attrs)) { - continue; - } + if (type != XmlPullParser.START_TAG) { + continue; + } - String name = parser.getName(); - T item = createItemFromTag(name, attrs); + if (onInterceptCreateItem(parser, parent, attrs)) { + continue; + } - onAddChildItem(parent, item); + String name = parser.getName(); + T item = createItemFromTag(name, attrs); - rInflate(parser, item, attrs); - } - } + onAddChildItem(parent, item); - /** - * Whether item creation should be intercepted to perform custom handling on the parser rather - * than creating an object from it. This is used in rare cases where a tag doesn't correspond - * to creation of an object. - * - * The parser will be pointing to the start of a tag, you must stop parsing and return when you - * reach the end of this element. That is, this method is responsible for parsing the element - * at the given position together with all of its child tags. - * - * Note that parsing of the root tag cannot be intercepted. - * - * @param parser XML dom node containing the description of the hierarchy. - * @param parent The item that should be the parent of whatever you create. - * @param attrs An AttributeSet of attributes to apply to the item. - * @return True to continue parsing without calling {@link #onCreateItem(String, AttributeSet)}, - * or false if this inflater should proceed to create an item. - */ - protected boolean onInterceptCreateItem(XmlPullParser parser, T parent, AttributeSet attrs) - throws XmlPullParserException { - return false; + rInflate(parser, item, attrs); } - - protected abstract void onAddChildItem(T parent, T child); + } + + /** + * Whether item creation should be intercepted to perform custom handling on the parser rather + * than creating an object from it. This is used in rare cases where a tag doesn't correspond to + * creation of an object. + * + * <p>The parser will be pointing to the start of a tag, you must stop parsing and return when you + * reach the end of this element. That is, this method is responsible for parsing the element at + * the given position together with all of its child tags. + * + * <p>Note that parsing of the root tag cannot be intercepted. + * + * @param parser XML dom node containing the description of the hierarchy. + * @param parent The item that should be the parent of whatever you create. + * @param attrs An AttributeSet of attributes to apply to the item. + * @return True to continue parsing without calling {@link #onCreateItem(String, AttributeSet)}, + * or false if this inflater should proceed to create an item. + */ + protected boolean onInterceptCreateItem(XmlPullParser parser, T parent, AttributeSet attrs) + throws XmlPullParserException { + return false; + } + + protected abstract void onAddChildItem(T parent, T child); } diff --git a/library/main/src/com/android/setupwizardlib/span/LinkSpan.java b/library/main/src/com/android/setupwizardlib/span/LinkSpan.java index 3dd783b..49ce1b9 100644 --- a/library/main/src/com/android/setupwizardlib/span/LinkSpan.java +++ b/library/main/src/com/android/setupwizardlib/span/LinkSpan.java @@ -20,6 +20,7 @@ import android.content.Context; import android.content.ContextWrapper; import android.graphics.Typeface; import android.os.Build; +import androidx.annotation.Nullable; import android.text.Selection; import android.text.Spannable; import android.text.TextPaint; @@ -28,126 +29,120 @@ import android.util.Log; import android.view.View; import android.widget.TextView; -import androidx.annotation.Nullable; - /** * A clickable span that will listen for click events and send it back to the context. To use this - * class, implement {@link OnLinkClickListener} in your TextView, or use - * {@link com.android.setupwizardlib.view.RichTextView#setOnClickListener(View.OnClickListener)}. + * class, implement {@link OnLinkClickListener} in your TextView, or use {@link + * com.android.setupwizardlib.view.RichTextView#setOnClickListener(View.OnClickListener)}. * - * <p />Note on accessibility: For TalkBack to be able to traverse and interact with the links, you + * <p>Note on accessibility: For TalkBack to be able to traverse and interact with the links, you * should use {@code LinkAccessibilityHelper} in your {@code TextView} subclass. Optionally you can * also use {@code RichTextView}, which includes link support. */ public class LinkSpan extends ClickableSpan { - /* - * Implementation note: When the orientation changes, TextView retains a reference to this span - * instead of writing it to a parcel (ClickableSpan is not Parcelable). If this class has any - * reference to the containing Activity (i.e. the activity context, or any views in the - * activity), it will cause memory leak. - */ + /* + * Implementation note: When the orientation changes, TextView retains a reference to this span + * instead of writing it to a parcel (ClickableSpan is not Parcelable). If this class has any + * reference to the containing Activity (i.e. the activity context, or any views in the + * activity), it will cause memory leak. + */ - /* static section */ + /* static section */ - private static final String TAG = "LinkSpan"; + private static final String TAG = "LinkSpan"; - private static final Typeface TYPEFACE_MEDIUM = - Typeface.create("sans-serif-medium", Typeface.NORMAL); + private static final Typeface TYPEFACE_MEDIUM = + Typeface.create("sans-serif-medium", Typeface.NORMAL); - /** - * @deprecated Use {@link OnLinkClickListener} - */ - @Deprecated - public interface OnClickListener { - void onClick(LinkSpan span); - } + /** @deprecated Use {@link OnLinkClickListener} */ + @Deprecated + public interface OnClickListener { + void onClick(LinkSpan span); + } + + /** + * Listener that is invoked when a link span is clicked. If the containing view of this span + * implements this interface, this will be invoked when the link is clicked. + */ + public interface OnLinkClickListener { /** - * Listener that is invoked when a link span is clicked. If the containing view of this span - * implements this interface, this will be invoked when the link is clicked. + * Called when a link has been clicked. + * + * @param span The span that was clicked. + * @return True if the click was handled, stopping further propagation of the click event. */ - public interface OnLinkClickListener { - - /** - * Called when a link has been clicked. - * - * @param span The span that was clicked. - * @return True if the click was handled, stopping further propagation of the click event. - */ - boolean onLinkClick(LinkSpan span); + boolean onLinkClick(LinkSpan span); + } + + /* non-static section */ + + private final String id; + + public LinkSpan(String id) { + this.id = id; + } + + @Override + public void onClick(View view) { + if (dispatchClick(view)) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + // Prevent the touch event from bubbling up to the parent views. + view.cancelPendingInputEvents(); + } + } else { + Log.w(TAG, "Dropping click event. No listener attached."); } - - /* non-static section */ - - private final String mId; - - public LinkSpan(String id) { - mId = id; + if (view instanceof TextView) { + // Remove the highlight effect when the click happens by clearing the selection + CharSequence text = ((TextView) view).getText(); + if (text instanceof Spannable) { + Selection.setSelection((Spannable) text, 0); + } } + } - @Override - public void onClick(View view) { - if (dispatchClick(view)) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - // Prevent the touch event from bubbling up to the parent views. - view.cancelPendingInputEvents(); - } - } else { - Log.w(TAG, "Dropping click event. No listener attached."); - } - if (view instanceof TextView) { - // Remove the highlight effect when the click happens by clearing the selection - CharSequence text = ((TextView) view).getText(); - if (text instanceof Spannable) { - Selection.setSelection((Spannable) text, 0); - } - } + private boolean dispatchClick(View view) { + boolean handled = false; + if (view instanceof OnLinkClickListener) { + handled = ((OnLinkClickListener) view).onLinkClick(this); } - - private boolean dispatchClick(View view) { - boolean handled = false; - if (view instanceof OnLinkClickListener) { - handled = ((OnLinkClickListener) view).onLinkClick(this); - } - if (!handled) { - final OnClickListener listener = getLegacyListenerFromContext(view.getContext()); - if (listener != null) { - listener.onClick(this); - handled = true; - } - } - return handled; + if (!handled) { + final OnClickListener listener = getLegacyListenerFromContext(view.getContext()); + if (listener != null) { + listener.onClick(this); + handled = true; + } } - - /** - * @deprecated Deprecated together with {@link OnClickListener} - */ - @Nullable - @Deprecated - private OnClickListener getLegacyListenerFromContext(@Nullable Context context) { - while (true) { - if (context instanceof OnClickListener) { - return (OnClickListener) context; - } else if (context instanceof ContextWrapper) { - // Unwrap any context wrapper, in base the base context implements onClickListener. - // ContextWrappers cannot have circular base contexts, so at some point this will - // reach the one of the other cases and return. - context = ((ContextWrapper) context).getBaseContext(); - } else { - return null; - } - } - } - - @Override - public void updateDrawState(TextPaint drawState) { - super.updateDrawState(drawState); - drawState.setUnderlineText(false); - drawState.setTypeface(TYPEFACE_MEDIUM); - } - - public String getId() { - return mId; + return handled; + } + + /** @deprecated Deprecated together with {@link OnClickListener} */ + @Nullable + @Deprecated + private OnClickListener getLegacyListenerFromContext(@Nullable Context context) { + while (true) { + if (context instanceof OnClickListener) { + return (OnClickListener) context; + } else if (context instanceof ContextWrapper) { + // Unwrap any context wrapper, in base the base context implements onClickListener. + // ContextWrappers cannot have circular base contexts, so at some point this will + // reach the one of the other cases and return. + context = ((ContextWrapper) context).getBaseContext(); + } else { + return null; + } } + } + + @Override + public void updateDrawState(TextPaint drawState) { + super.updateDrawState(drawState); + drawState.setUnderlineText(false); + drawState.setTypeface(TYPEFACE_MEDIUM); + } + + public String getId() { + return id; + } } diff --git a/library/main/src/com/android/setupwizardlib/span/SpanHelper.java b/library/main/src/com/android/setupwizardlib/span/SpanHelper.java index d75e338..4037e6d 100644 --- a/library/main/src/com/android/setupwizardlib/span/SpanHelper.java +++ b/library/main/src/com/android/setupwizardlib/span/SpanHelper.java @@ -23,14 +23,14 @@ import android.text.Spannable; */ public class SpanHelper { - /** - * Add {@code newSpan} at the same start and end indices as {@code oldSpan} and remove - * {@code oldSpan} from the {@code spannable}. - */ - public static void replaceSpan(Spannable spannable, Object oldSpan, Object newSpan) { - final int spanStart = spannable.getSpanStart(oldSpan); - final int spanEnd = spannable.getSpanEnd(oldSpan); - spannable.removeSpan(oldSpan); - spannable.setSpan(newSpan, spanStart, spanEnd, 0); - } + /** + * Add {@code newSpan} at the same start and end indices as {@code oldSpan} and remove {@code + * oldSpan} from the {@code spannable}. + */ + public static void replaceSpan(Spannable spannable, Object oldSpan, Object newSpan) { + final int spanStart = spannable.getSpanStart(oldSpan); + final int spanEnd = spannable.getSpanEnd(oldSpan); + spannable.removeSpan(oldSpan); + spannable.setSpan(newSpan, spanStart, spanEnd, 0); + } } diff --git a/library/main/src/com/android/setupwizardlib/template/ButtonFooterMixin.java b/library/main/src/com/android/setupwizardlib/template/ButtonFooterMixin.java index a8580a3..c872f6b 100644 --- a/library/main/src/com/android/setupwizardlib/template/ButtonFooterMixin.java +++ b/library/main/src/com/android/setupwizardlib/template/ButtonFooterMixin.java @@ -18,6 +18,10 @@ package com.android.setupwizardlib.template; import android.annotation.SuppressLint; import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.StringRes; +import androidx.annotation.StyleRes; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; @@ -25,12 +29,6 @@ import android.view.ViewStub; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.StringRes; -import androidx.annotation.StyleRes; - import com.android.setupwizardlib.R; import com.android.setupwizardlib.TemplateLayout; @@ -41,134 +39,131 @@ import com.android.setupwizardlib.TemplateLayout; */ public class ButtonFooterMixin implements Mixin { - private final Context mContext; - - @Nullable - private final ViewStub mFooterStub; - - private LinearLayout mButtonContainer; - - /** - * Create a mixin for managing buttons on the footer. - * - * @param layout The {@link TemplateLayout} containing this mixin. - */ - public ButtonFooterMixin(TemplateLayout layout) { - mContext = layout.getContext(); - mFooterStub = (ViewStub) layout.findManagedViewById(R.id.suw_layout_footer); - } - - /** - * Add a button with the given text and style. Common style for GLIF are - * {@code SuwGlifButton.Primary} and {@code SuwGlifButton.Secondary}. - * - * @param text The label for the button. - * @param theme Theme resource to be used for this button. Since this is applied as a theme, - * the resource will typically apply {@code android:buttonStyle} so it will be - * applied to the button as a style as well. - * - * @return The button that was created. - */ - public Button addButton(CharSequence text, @StyleRes int theme) { - Button button = createThemedButton(mContext, theme); - button.setText(text); - return addButton(button); - } - - /** - * Add a button with the given text and style. Common style for GLIF are - * {@code SuwGlifButton.Primary} and {@code SuwGlifButton.Secondary}. - * - * @param text The label for the button. - * @param theme Theme resource to be used for this button. Since this is applied as a theme, - * the resource will typically apply {@code android:buttonStyle} so it will be - * applied to the button as a style as well. - * - * @return The button that was created. - */ - public Button addButton(@StringRes int text, @StyleRes int theme) { - Button button = createThemedButton(mContext, theme); - button.setText(text); - return addButton(button); - } - - /** - * Add a button to the footer. - * - * @param button The button to be added to the footer. - * @return The button that was added. - */ - public Button addButton(Button button) { - final LinearLayout buttonContainer = ensureFooterInflated(); - buttonContainer.addView(button); - return button; - } - - /** - * Add a space to the footer. Spaces will share the remaining space of footer, so for example, - * [Button] [space] [Button] [space] [Button] will give you 3 buttons, left, center, and right - * aligned. - * - * @return The view that was used as space. - */ - public View addSpace() { - final LinearLayout buttonContainer = ensureFooterInflated(); - View space = new View(buttonContainer.getContext()); - space.setLayoutParams(new LayoutParams(0, 0, 1.0f)); - space.setVisibility(View.INVISIBLE); - buttonContainer.addView(space); - return space; + private final Context context; + + @Nullable private final ViewStub footerStub; + + private LinearLayout buttonContainer; + + /** + * Create a mixin for managing buttons on the footer. + * + * @param layout The {@link TemplateLayout} containing this mixin. + */ + public ButtonFooterMixin(TemplateLayout layout) { + context = layout.getContext(); + footerStub = (ViewStub) layout.findManagedViewById(R.id.suw_layout_footer); + } + + /** + * Add a button with the given text and style. Common style for GLIF are {@code + * SuwGlifButton.Primary} and {@code SuwGlifButton.Secondary}. + * + * @param text The label for the button. + * @param theme Theme resource to be used for this button. Since this is applied as a theme, the + * resource will typically apply {@code android:buttonStyle} so it will be applied to the + * button as a style as well. + * @return The button that was created. + */ + public Button addButton(CharSequence text, @StyleRes int theme) { + Button button = createThemedButton(context, theme); + button.setText(text); + return addButton(button); + } + + /** + * Add a button with the given text and style. Common style for GLIF are {@code + * SuwGlifButton.Primary} and {@code SuwGlifButton.Secondary}. + * + * @param text The label for the button. + * @param theme Theme resource to be used for this button. Since this is applied as a theme, the + * resource will typically apply {@code android:buttonStyle} so it will be applied to the + * button as a style as well. + * @return The button that was created. + */ + public Button addButton(@StringRes int text, @StyleRes int theme) { + Button button = createThemedButton(context, theme); + button.setText(text); + return addButton(button); + } + + /** + * Add a button to the footer. + * + * @param button The button to be added to the footer. + * @return The button that was added. + */ + public Button addButton(Button button) { + final LinearLayout buttonContainer = ensureFooterInflated(); + buttonContainer.addView(button); + return button; + } + + /** + * Add a space to the footer. Spaces will share the remaining space of footer, so for example, + * [Button] [space] [Button] [space] [Button] will give you 3 buttons, left, center, and right + * aligned. + * + * @return The view that was used as space. + */ + public View addSpace() { + final LinearLayout buttonContainer = ensureFooterInflated(); + View space = new View(buttonContainer.getContext()); + space.setLayoutParams(new LayoutParams(0, 0, 1.0f)); + space.setVisibility(View.INVISIBLE); + buttonContainer.addView(space); + return space; + } + + /** + * Remove a previously added button. + * + * @param button The button to be removed. + */ + public void removeButton(Button button) { + if (buttonContainer != null) { + buttonContainer.removeView(button); } - - /** - * Remove a previously added button. - * - * @param button The button to be removed. - */ - public void removeButton(Button button) { - if (mButtonContainer != null) { - mButtonContainer.removeView(button); - } - } - - /** - * Remove a previously added space. - * - * @param space The space to be removed. - */ - public void removeSpace(View space) { - if (mButtonContainer != null) { - mButtonContainer.removeView(space); - } + } + + /** + * Remove a previously added space. + * + * @param space The space to be removed. + */ + public void removeSpace(View space) { + if (buttonContainer != null) { + buttonContainer.removeView(space); } - - /** - * Remove all views, including spaces, from the footer. Note that if the footer container is - * already inflated, this will not remove the container itself. - */ - public void removeAllViews() { - if (mButtonContainer != null) { - mButtonContainer.removeAllViews(); - } + } + + /** + * Remove all views, including spaces, from the footer. Note that if the footer container is + * already inflated, this will not remove the container itself. + */ + public void removeAllViews() { + if (buttonContainer != null) { + buttonContainer.removeAllViews(); } - - @NonNull - private LinearLayout ensureFooterInflated() { - if (mButtonContainer == null) { - if (mFooterStub == null) { - throw new IllegalStateException("Footer stub is not found in this template"); - } - mFooterStub.setLayoutResource(R.layout.suw_glif_footer_button_bar); - mButtonContainer = (LinearLayout) mFooterStub.inflate(); - } - return mButtonContainer; - } - - @SuppressLint("InflateParams") - private Button createThemedButton(Context context, @StyleRes int theme) { - // Inflate a single button from XML, which when using support lib, will take advantage of - // the injected layout inflater and give us AppCompatButton instead. - LayoutInflater inflater = LayoutInflater.from(new ContextThemeWrapper(context, theme)); - return (Button) inflater.inflate(R.layout.suw_button, null, false); + } + + @NonNull + private LinearLayout ensureFooterInflated() { + if (buttonContainer == null) { + if (footerStub == null) { + throw new IllegalStateException("Footer stub is not found in this template"); + } + footerStub.setLayoutResource(R.layout.suw_glif_footer_button_bar); + buttonContainer = (LinearLayout) footerStub.inflate(); } + return buttonContainer; + } + + @SuppressLint("InflateParams") + private Button createThemedButton(Context context, @StyleRes int theme) { + // Inflate a single button from XML, which when using support lib, will take advantage of + // the injected layout inflater and give us AppCompatButton instead. + LayoutInflater inflater = LayoutInflater.from(new ContextThemeWrapper(context, theme)); + return (Button) inflater.inflate(R.layout.suw_button, null, false); + } } diff --git a/library/main/src/com/android/setupwizardlib/template/ColoredHeaderMixin.java b/library/main/src/com/android/setupwizardlib/template/ColoredHeaderMixin.java index ccc5aad..acdaa67 100644 --- a/library/main/src/com/android/setupwizardlib/template/ColoredHeaderMixin.java +++ b/library/main/src/com/android/setupwizardlib/template/ColoredHeaderMixin.java @@ -20,54 +20,51 @@ import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.TextView; - import com.android.setupwizardlib.R; import com.android.setupwizardlib.TemplateLayout; /** * A {@link Mixin} displaying a header text that can be set to different colors. This Mixin is - * registered to the tempalte using HeaderMixin.class, and can be retrieved using: - * {@code (ColoredHeaderMixin) templateLayout.getMixin(HeaderMixin.class}. + * registered to the template using HeaderMixin.class, and can be retrieved using: {@code + * (ColoredHeaderMixin) templateLayout.getMixin(HeaderMixin.class}. */ public class ColoredHeaderMixin extends HeaderMixin { - /** - * {@inheritDoc} - */ - public ColoredHeaderMixin(TemplateLayout layout, AttributeSet attrs, int defStyleAttr) { - super(layout, attrs, defStyleAttr); - - final TypedArray a = layout.getContext().obtainStyledAttributes( - attrs, R.styleable.SuwColoredHeaderMixin, defStyleAttr, 0); + /** {@inheritDoc} */ + public ColoredHeaderMixin(TemplateLayout layout, AttributeSet attrs, int defStyleAttr) { + super(layout, attrs, defStyleAttr); - // Set the header color - final ColorStateList headerColor = - a.getColorStateList(R.styleable.SuwColoredHeaderMixin_suwHeaderColor); - if (headerColor != null) { - setColor(headerColor); - } + final TypedArray a = + layout + .getContext() + .obtainStyledAttributes(attrs, R.styleable.SuwColoredHeaderMixin, defStyleAttr, 0); - a.recycle(); + // Set the header color + final ColorStateList headerColor = + a.getColorStateList(R.styleable.SuwColoredHeaderMixin_suwHeaderColor); + if (headerColor != null) { + setColor(headerColor); } - /** - * Sets the color of the header text. This can also be set via XML using - * {@code app:suwHeaderColor}. - * - * @param color The text color of the header. - */ - public void setColor(ColorStateList color) { - final TextView titleView = getTextView(); - if (titleView != null) { - titleView.setTextColor(color); - } - } + a.recycle(); + } - /** - * @return The current text color of the header. - */ - public ColorStateList getColor() { - final TextView titleView = getTextView(); - return titleView != null ? titleView.getTextColors() : null; + /** + * Sets the color of the header text. This can also be set via XML using {@code + * app:suwHeaderColor}. + * + * @param color The text color of the header. + */ + public void setColor(ColorStateList color) { + final TextView titleView = getTextView(); + if (titleView != null) { + titleView.setTextColor(color); } + } + + /** @return The current text color of the header. */ + public ColorStateList getColor() { + final TextView titleView = getTextView(); + return titleView != null ? titleView.getTextColors() : null; + } } diff --git a/library/main/src/com/android/setupwizardlib/template/HeaderMixin.java b/library/main/src/com/android/setupwizardlib/template/HeaderMixin.java index 604de9a..7d7fb4a 100644 --- a/library/main/src/com/android/setupwizardlib/template/HeaderMixin.java +++ b/library/main/src/com/android/setupwizardlib/template/HeaderMixin.java @@ -17,80 +17,74 @@ package com.android.setupwizardlib.template; import android.content.res.TypedArray; -import android.util.AttributeSet; -import android.widget.TextView; - import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; - +import android.util.AttributeSet; +import android.widget.TextView; import com.android.setupwizardlib.R; import com.android.setupwizardlib.TemplateLayout; -/** - * A {@link Mixin} for setting and getting the header text. - */ +/** A {@link Mixin} for setting and getting the header text. */ public class HeaderMixin implements Mixin { - private TemplateLayout mTemplateLayout; - - /** - * @param layout The layout this Mixin belongs to. - * @param attrs XML attributes given to the layout. - * @param defStyleAttr The default style attribute as given to the constructor of the layout. - */ - public HeaderMixin(@NonNull TemplateLayout layout, @Nullable AttributeSet attrs, - @AttrRes int defStyleAttr) { - mTemplateLayout = layout; + private final TemplateLayout templateLayout; - final TypedArray a = layout.getContext().obtainStyledAttributes( - attrs, R.styleable.SuwHeaderMixin, defStyleAttr, 0); + /** + * @param layout The layout this Mixin belongs to. + * @param attrs XML attributes given to the layout. + * @param defStyleAttr The default style attribute as given to the constructor of the layout. + */ + public HeaderMixin( + @NonNull TemplateLayout layout, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { + templateLayout = layout; - // Set the header text - final CharSequence headerText = a.getText(R.styleable.SuwHeaderMixin_suwHeaderText); - if (headerText != null) { - setText(headerText); - } + final TypedArray a = + layout + .getContext() + .obtainStyledAttributes(attrs, R.styleable.SuwHeaderMixin, defStyleAttr, 0); - a.recycle(); + // Set the header text + final CharSequence headerText = a.getText(R.styleable.SuwHeaderMixin_suwHeaderText); + if (headerText != null) { + setText(headerText); } - /** - * @return The TextView displaying the header. - */ - public TextView getTextView() { - return (TextView) mTemplateLayout.findManagedViewById(R.id.suw_layout_title); - } + a.recycle(); + } - /** - * Sets the header text. This can also be set via the XML attribute {@code app:suwHeaderText}. - * - * @param title The resource ID of the text to be set as header. - */ - public void setText(int title) { - final TextView titleView = getTextView(); - if (titleView != null) { - titleView.setText(title); - } - } + /** @return The TextView displaying the header. */ + public TextView getTextView() { + return (TextView) templateLayout.findManagedViewById(R.id.suw_layout_title); + } - /** - * Sets the header text. This can also be set via the XML attribute {@code app:suwHeaderText}. - * - * @param title The text to be set as header. - */ - public void setText(CharSequence title) { - final TextView titleView = getTextView(); - if (titleView != null) { - titleView.setText(title); - } + /** + * Sets the header text. This can also be set via the XML attribute {@code app:suwHeaderText}. + * + * @param title The resource ID of the text to be set as header. + */ + public void setText(int title) { + final TextView titleView = getTextView(); + if (titleView != null) { + titleView.setText(title); } + } - /** - * @return The current header text. - */ - public CharSequence getText() { - final TextView titleView = getTextView(); - return titleView != null ? titleView.getText() : null; + /** + * Sets the header text. This can also be set via the XML attribute {@code app:suwHeaderText}. + * + * @param title The text to be set as header. + */ + public void setText(CharSequence title) { + final TextView titleView = getTextView(); + if (titleView != null) { + titleView.setText(title); } + } + + /** @return The current header text. */ + public CharSequence getText() { + final TextView titleView = getTextView(); + return titleView != null ? titleView.getText() : null; + } } diff --git a/library/main/src/com/android/setupwizardlib/template/IconMixin.java b/library/main/src/com/android/setupwizardlib/template/IconMixin.java index 5f5c915..e28f67d 100644 --- a/library/main/src/com/android/setupwizardlib/template/IconMixin.java +++ b/library/main/src/com/android/setupwizardlib/template/IconMixin.java @@ -19,100 +19,88 @@ package com.android.setupwizardlib.template; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; +import androidx.annotation.DrawableRes; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; - -import androidx.annotation.DrawableRes; - import com.android.setupwizardlib.R; import com.android.setupwizardlib.TemplateLayout; -/** - * A {@link Mixin} for setting an icon on the template layout. - */ +/** A {@link Mixin} for setting an icon on the template layout. */ public class IconMixin implements Mixin { - private TemplateLayout mTemplateLayout; - - /** - * @param layout The template layout that this Mixin is a part of. - * @param attrs XML attributes given to the layout. - * @param defStyleAttr The default style attribute as given to the constructor of the layout. - */ - public IconMixin(TemplateLayout layout, AttributeSet attrs, int defStyleAttr) { - mTemplateLayout = layout; - final Context context = layout.getContext(); - - final TypedArray a = - context.obtainStyledAttributes(attrs, R.styleable.SuwIconMixin, defStyleAttr, 0); + private final TemplateLayout templateLayout; - final @DrawableRes int icon = a.getResourceId(R.styleable.SuwIconMixin_android_icon, 0); - if (icon != 0) { - setIcon(icon); - } + /** + * @param layout The template layout that this Mixin is a part of. + * @param attrs XML attributes given to the layout. + * @param defStyleAttr The default style attribute as given to the constructor of the layout. + */ + public IconMixin(TemplateLayout layout, AttributeSet attrs, int defStyleAttr) { + templateLayout = layout; + final Context context = layout.getContext(); - a.recycle(); - } - - /** - * Sets the icon on this layout. The icon can also be set in XML using {@code android:icon}. - * - * @param icon A drawable icon. - */ - public void setIcon(Drawable icon) { - final ImageView iconView = getView(); - if (iconView != null) { - iconView.setImageDrawable(icon); - iconView.setVisibility(icon != null ? View.VISIBLE : View.GONE); - } - } + final TypedArray a = + context.obtainStyledAttributes(attrs, R.styleable.SuwIconMixin, defStyleAttr, 0); - /** - * Sets the icon on this layout. The icon can also be set in XML using {@code android:icon}. - * - * @param icon A drawable icon resource. - */ - public void setIcon(@DrawableRes int icon) { - final ImageView iconView = getView(); - if (iconView != null) { - // Note: setImageResource on the ImageView is overridden in AppCompatImageView for - // support lib users, which enables vector drawable compat to work on versions pre-L. - iconView.setImageResource(icon); - iconView.setVisibility(icon != 0 ? View.VISIBLE : View.GONE); - } + final @DrawableRes int icon = a.getResourceId(R.styleable.SuwIconMixin_android_icon, 0); + if (icon != 0) { + setIcon(icon); } - /** - * @return The icon previously set in {@link #setIcon(Drawable)} or {@code android:icon} - */ - public Drawable getIcon() { - final ImageView iconView = getView(); - return iconView != null ? iconView.getDrawable() : null; + a.recycle(); + } + + /** + * Sets the icon on this layout. The icon can also be set in XML using {@code android:icon}. + * + * @param icon A drawable icon. + */ + public void setIcon(Drawable icon) { + final ImageView iconView = getView(); + if (iconView != null) { + iconView.setImageDrawable(icon); + iconView.setVisibility(icon != null ? View.VISIBLE : View.GONE); } - - /** - * Sets the content description of the icon view - */ - public void setContentDescription(CharSequence description) { - final ImageView iconView = getView(); - if (iconView != null) { - iconView.setContentDescription(description); - } + } + + /** + * Sets the icon on this layout. The icon can also be set in XML using {@code android:icon}. + * + * @param icon A drawable icon resource. + */ + public void setIcon(@DrawableRes int icon) { + final ImageView iconView = getView(); + if (iconView != null) { + // Note: setImageResource on the ImageView is overridden in AppCompatImageView for + // support lib users, which enables vector drawable compat to work on versions pre-L. + iconView.setImageResource(icon); + iconView.setVisibility(icon != 0 ? View.VISIBLE : View.GONE); } - - /** - * @return The content description of the icon view - */ - public CharSequence getContentDescription() { - final ImageView iconView = getView(); - return iconView != null ? iconView.getContentDescription() : null; - } - - /** - * @return The ImageView responsible for displaying the icon. - */ - protected ImageView getView() { - return (ImageView) mTemplateLayout.findManagedViewById(R.id.suw_layout_icon); + } + + /** @return The icon previously set in {@link #setIcon(Drawable)} or {@code android:icon} */ + public Drawable getIcon() { + final ImageView iconView = getView(); + return iconView != null ? iconView.getDrawable() : null; + } + + /** Sets the content description of the icon view */ + public void setContentDescription(CharSequence description) { + final ImageView iconView = getView(); + if (iconView != null) { + iconView.setContentDescription(description); } + } + + /** @return The content description of the icon view */ + public CharSequence getContentDescription() { + final ImageView iconView = getView(); + return iconView != null ? iconView.getContentDescription() : null; + } + + /** @return The ImageView responsible for displaying the icon. */ + protected ImageView getView() { + return (ImageView) templateLayout.findManagedViewById(R.id.suw_layout_icon); + } } diff --git a/library/main/src/com/android/setupwizardlib/template/ListMixin.java b/library/main/src/com/android/setupwizardlib/template/ListMixin.java index cbc29b5..066141e 100644 --- a/library/main/src/com/android/setupwizardlib/template/ListMixin.java +++ b/library/main/src/com/android/setupwizardlib/template/ListMixin.java @@ -21,16 +21,14 @@ import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Build.VERSION_CODES; +import androidx.annotation.AttrRes; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.widget.HeaderViewListAdapter; import android.widget.ListAdapter; import android.widget.ListView; - -import androidx.annotation.AttrRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - import com.android.setupwizardlib.R; import com.android.setupwizardlib.TemplateLayout; import com.android.setupwizardlib.items.ItemAdapter; @@ -38,188 +36,170 @@ import com.android.setupwizardlib.items.ItemGroup; import com.android.setupwizardlib.items.ItemInflater; import com.android.setupwizardlib.util.DrawableLayoutDirectionHelper; -/** - * A {@link Mixin} for interacting with ListViews. - */ +/** A {@link Mixin} for interacting with ListViews. */ public class ListMixin implements Mixin { - private TemplateLayout mTemplateLayout; - - @Nullable - private ListView mListView; - - private Drawable mDivider; - private Drawable mDefaultDivider; - - private int mDividerInsetStart; - private int mDividerInsetEnd; - - /** - * @param layout The layout this mixin belongs to. - */ - public ListMixin(@NonNull TemplateLayout layout, @Nullable AttributeSet attrs, - @AttrRes int defStyleAttr) { - mTemplateLayout = layout; - - final Context context = layout.getContext(); - final TypedArray a = context.obtainStyledAttributes( - attrs, R.styleable.SuwListMixin, defStyleAttr, 0); - - final int entries = a.getResourceId(R.styleable.SuwListMixin_android_entries, 0); - if (entries != 0) { - final ItemGroup inflated = - (ItemGroup) new ItemInflater(context).inflate(entries); - setAdapter(new ItemAdapter(inflated)); - } - int dividerInset = - a.getDimensionPixelSize(R.styleable.SuwListMixin_suwDividerInset, -1); - if (dividerInset != -1) { - setDividerInset(dividerInset); - } else { - int dividerInsetStart = - a.getDimensionPixelSize(R.styleable.SuwListMixin_suwDividerInsetStart, 0); - int dividerInsetEnd = - a.getDimensionPixelSize(R.styleable.SuwListMixin_suwDividerInsetEnd, 0); - setDividerInsets(dividerInsetStart, dividerInsetEnd); - } - a.recycle(); - } + private final TemplateLayout templateLayout; - /** - * @return The list view contained in the layout, as marked by {@code @android:id/list}. This - * will return {@code null} if the list doesn't exist in the layout. - */ - public ListView getListView() { - return getListViewInternal(); - } + @Nullable private ListView listView; - // Client code can assume getListView() will not be null if they know their template contains - // the list, but this mixin cannot. Any usages of getListView in this mixin needs null checks. - @Nullable - private ListView getListViewInternal() { - if (mListView == null) { - final View list = mTemplateLayout.findManagedViewById(android.R.id.list); - if (list instanceof ListView) { - mListView = (ListView) list; - } - } - return mListView; - } + private Drawable divider; + private Drawable defaultDivider; - /** - * List mixin needs to update the dividers if the layout direction has changed. This method - * should be called when {@link View#onLayout(boolean, int, int, int, int)} of the template - * is called. - */ - public void onLayout() { - if (mDivider == null) { - // Update divider in case layout direction has just been resolved - updateDivider(); - } - } + private int dividerInsetStart; + private int dividerInsetEnd; - /** - * Gets the adapter of the list view in this layout. If the adapter is a HeaderViewListAdapter, - * this method will unwrap it and return the underlying adapter. - * - * @return The adapter, or {@code null} if there is no list, or if the list has no adapter. - */ - public ListAdapter getAdapter() { - final ListView listView = getListViewInternal(); - if (listView != null) { - final ListAdapter adapter = listView.getAdapter(); - if (adapter instanceof HeaderViewListAdapter) { - return ((HeaderViewListAdapter) adapter).getWrappedAdapter(); - } - return adapter; - } - return null; - } + /** @param layout The layout this mixin belongs to. */ + public ListMixin( + @NonNull TemplateLayout layout, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { + templateLayout = layout; - /** - * Sets the adapter on the list view in this layout. - */ - public void setAdapter(ListAdapter adapter) { - final ListView listView = getListViewInternal(); - if (listView != null) { - listView.setAdapter(adapter); - } - } + final Context context = layout.getContext(); + final TypedArray a = + context.obtainStyledAttributes(attrs, R.styleable.SuwListMixin, defStyleAttr, 0); - /** - * @deprecated Use {@link #setDividerInsets(int, int)} instead. - */ - @Deprecated - public void setDividerInset(int inset) { - setDividerInsets(inset, 0); + final int entries = a.getResourceId(R.styleable.SuwListMixin_android_entries, 0); + if (entries != 0) { + final ItemGroup inflated = (ItemGroup) new ItemInflater(context).inflate(entries); + setAdapter(new ItemAdapter(inflated)); } - - /** - * Sets the start inset of the divider. This will use the default divider drawable set in the - * theme and apply insets to it. - * - * @param start The number of pixels to inset on the "start" side of the list divider. Typically - * this will be either {@code @dimen/suw_items_glif_icon_divider_inset} or - * {@code @dimen/suw_items_glif_text_divider_inset}. - * @param end The number of pixels to inset on the "end" side of the list divider. - */ - public void setDividerInsets(int start, int end) { - mDividerInsetStart = start; - mDividerInsetEnd = end; - updateDivider(); + int dividerInset = a.getDimensionPixelSize(R.styleable.SuwListMixin_suwDividerInset, -1); + if (dividerInset != -1) { + setDividerInset(dividerInset); + } else { + int dividerInsetStart = + a.getDimensionPixelSize(R.styleable.SuwListMixin_suwDividerInsetStart, 0); + int dividerInsetEnd = a.getDimensionPixelSize(R.styleable.SuwListMixin_suwDividerInsetEnd, 0); + setDividerInsets(dividerInsetStart, dividerInsetEnd); } - - /** - * @return The number of pixels inset on the start side of the divider. - * @deprecated This is the same as {@link #getDividerInsetStart()}. Use that instead. - */ - @Deprecated - public int getDividerInset() { - return getDividerInsetStart(); + a.recycle(); + } + + /** + * @return The list view contained in the layout, as marked by {@code @android:id/list}. This will + * return {@code null} if the list doesn't exist in the layout. + */ + public ListView getListView() { + return getListViewInternal(); + } + + // Client code can assume getListView() will not be null if they know their template contains + // the list, but this mixin cannot. Any usages of getListView in this mixin needs null checks. + @Nullable + private ListView getListViewInternal() { + if (listView == null) { + final View list = templateLayout.findManagedViewById(android.R.id.list); + if (list instanceof ListView) { + listView = (ListView) list; + } } - - /** - * @return The number of pixels inset on the start side of the divider. - */ - public int getDividerInsetStart() { - return mDividerInsetStart; + return listView; + } + + /** + * List mixin needs to update the dividers if the layout direction has changed. This method should + * be called when {@link View#onLayout(boolean, int, int, int, int)} of the template is called. + */ + public void onLayout() { + if (divider == null) { + // Update divider in case layout direction has just been resolved + updateDivider(); } - - /** - * @return The number of pixels inset on the end side of the divider. - */ - public int getDividerInsetEnd() { - return mDividerInsetEnd; + } + + /** + * Gets the adapter of the list view in this layout. If the adapter is a HeaderViewListAdapter, + * this method will unwrap it and return the underlying adapter. + * + * @return The adapter, or {@code null} if there is no list, or if the list has no adapter. + */ + public ListAdapter getAdapter() { + final ListView listView = getListViewInternal(); + if (listView != null) { + final ListAdapter adapter = listView.getAdapter(); + if (adapter instanceof HeaderViewListAdapter) { + return ((HeaderViewListAdapter) adapter).getWrappedAdapter(); + } + return adapter; } - - private void updateDivider() { - final ListView listView = getListViewInternal(); - if (listView == null) { - return; - } - boolean shouldUpdate = true; - if (Build.VERSION.SDK_INT >= VERSION_CODES.KITKAT) { - shouldUpdate = mTemplateLayout.isLayoutDirectionResolved(); - } - if (shouldUpdate) { - if (mDefaultDivider == null) { - mDefaultDivider = listView.getDivider(); - } - mDivider = DrawableLayoutDirectionHelper.createRelativeInsetDrawable( - mDefaultDivider, - mDividerInsetStart /* start */, - 0 /* top */, - mDividerInsetEnd /* end */, - 0 /* bottom */, - mTemplateLayout); - listView.setDivider(mDivider); - } + return null; + } + + /** Sets the adapter on the list view in this layout. */ + public void setAdapter(ListAdapter adapter) { + final ListView listView = getListViewInternal(); + if (listView != null) { + listView.setAdapter(adapter); } - - /** - * @return The drawable used as the divider. - */ - public Drawable getDivider() { - return mDivider; + } + + /** @deprecated Use {@link #setDividerInsets(int, int)} instead. */ + @Deprecated + public void setDividerInset(int inset) { + setDividerInsets(inset, 0); + } + + /** + * Sets the start inset of the divider. This will use the default divider drawable set in the + * theme and apply insets to it. + * + * @param start The number of pixels to inset on the "start" side of the list divider. Typically + * this will be either {@code @dimen/suw_items_glif_icon_divider_inset} or + * {@code @dimen/suw_items_glif_text_divider_inset}. + * @param end The number of pixels to inset on the "end" side of the list divider. + */ + public void setDividerInsets(int start, int end) { + dividerInsetStart = start; + dividerInsetEnd = end; + updateDivider(); + } + + /** + * @return The number of pixels inset on the start side of the divider. + * @deprecated This is the same as {@link #getDividerInsetStart()}. Use that instead. + */ + @Deprecated + public int getDividerInset() { + return getDividerInsetStart(); + } + + /** @return The number of pixels inset on the start side of the divider. */ + public int getDividerInsetStart() { + return dividerInsetStart; + } + + /** @return The number of pixels inset on the end side of the divider. */ + public int getDividerInsetEnd() { + return dividerInsetEnd; + } + + private void updateDivider() { + final ListView listView = getListViewInternal(); + if (listView == null) { + return; } + boolean shouldUpdate = true; + if (Build.VERSION.SDK_INT >= VERSION_CODES.KITKAT) { + shouldUpdate = templateLayout.isLayoutDirectionResolved(); + } + if (shouldUpdate) { + if (defaultDivider == null) { + defaultDivider = listView.getDivider(); + } + divider = + DrawableLayoutDirectionHelper.createRelativeInsetDrawable( + defaultDivider, + dividerInsetStart /* start */, + 0 /* top */, + dividerInsetEnd /* end */, + 0 /* bottom */, + templateLayout); + listView.setDivider(divider); + } + } + + /** @return The drawable used as the divider. */ + public Drawable getDivider() { + return divider; + } } diff --git a/library/main/src/com/android/setupwizardlib/template/ListViewScrollHandlingDelegate.java b/library/main/src/com/android/setupwizardlib/template/ListViewScrollHandlingDelegate.java index faea305..8614ff4 100644 --- a/library/main/src/com/android/setupwizardlib/template/ListViewScrollHandlingDelegate.java +++ b/library/main/src/com/android/setupwizardlib/template/ListViewScrollHandlingDelegate.java @@ -16,73 +16,67 @@ package com.android.setupwizardlib.template; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import android.util.Log; import android.widget.AbsListView; import android.widget.ListAdapter; import android.widget.ListView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - import com.android.setupwizardlib.template.RequireScrollMixin.ScrollHandlingDelegate; /** - * {@link ScrollHandlingDelegate} which analyzes scroll events from {@link ListView} and - * notifies {@link RequireScrollMixin} about scrollability changes. + * {@link ScrollHandlingDelegate} which analyzes scroll events from {@link ListView} and notifies + * {@link RequireScrollMixin} about scrollability changes. */ -public class ListViewScrollHandlingDelegate implements ScrollHandlingDelegate, - AbsListView.OnScrollListener { +public class ListViewScrollHandlingDelegate + implements ScrollHandlingDelegate, AbsListView.OnScrollListener { - private static final String TAG = "ListViewDelegate"; + private static final String TAG = "ListViewDelegate"; - private static final int SCROLL_DURATION = 500; + private static final int SCROLL_DURATION = 500; - @NonNull - private final RequireScrollMixin mRequireScrollMixin; + @NonNull private final RequireScrollMixin requireScrollMixin; - @Nullable - private final ListView mListView; + @Nullable private final ListView listView; - public ListViewScrollHandlingDelegate( - @NonNull RequireScrollMixin requireScrollMixin, - @Nullable ListView listView) { - mRequireScrollMixin = requireScrollMixin; - mListView = listView; - } + public ListViewScrollHandlingDelegate( + @NonNull RequireScrollMixin requireScrollMixin, @Nullable ListView listView) { + this.requireScrollMixin = requireScrollMixin; + this.listView = listView; + } - @Override - public void startListening() { - if (mListView != null) { - mListView.setOnScrollListener(this); + @Override + public void startListening() { + if (listView != null) { + listView.setOnScrollListener(this); - final ListAdapter adapter = mListView.getAdapter(); - if (mListView.getLastVisiblePosition() < adapter.getCount()) { - mRequireScrollMixin.notifyScrollabilityChange(true); - } - } else { - Log.w(TAG, "Cannot require scroll. List view is null"); - } + final ListAdapter adapter = listView.getAdapter(); + if (listView.getLastVisiblePosition() < adapter.getCount()) { + requireScrollMixin.notifyScrollabilityChange(true); + } + } else { + Log.w(TAG, "Cannot require scroll. List view is null"); } + } - @Override - public void pageScrollDown() { - if (mListView != null) { - final int height = mListView.getHeight(); - mListView.smoothScrollBy(height, SCROLL_DURATION); - } + @Override + public void pageScrollDown() { + if (listView != null) { + final int height = listView.getHeight(); + listView.smoothScrollBy(height, SCROLL_DURATION); } + } - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - } + @Override + public void onScrollStateChanged(AbsListView view, int scrollState) {} - @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, - int totalItemCount) { - if (firstVisibleItem + visibleItemCount >= totalItemCount) { - mRequireScrollMixin.notifyScrollabilityChange(false); - } else { - mRequireScrollMixin.notifyScrollabilityChange(true); - } + @Override + public void onScroll( + AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (firstVisibleItem + visibleItemCount >= totalItemCount) { + requireScrollMixin.notifyScrollabilityChange(false); + } else { + requireScrollMixin.notifyScrollabilityChange(true); } + } } diff --git a/library/main/src/com/android/setupwizardlib/template/Mixin.java b/library/main/src/com/android/setupwizardlib/template/Mixin.java index b7b8893..b460777 100644 --- a/library/main/src/com/android/setupwizardlib/template/Mixin.java +++ b/library/main/src/com/android/setupwizardlib/template/Mixin.java @@ -22,5 +22,4 @@ package com.android.setupwizardlib.template; * @see com.android.setupwizardlib.TemplateLayout#registerMixin(Class, Mixin) * @see com.android.setupwizardlib.TemplateLayout#getMixin(Class) */ -public interface Mixin { -} +public interface Mixin {} diff --git a/library/main/src/com/android/setupwizardlib/template/NavigationBarMixin.java b/library/main/src/com/android/setupwizardlib/template/NavigationBarMixin.java index df35017..2412eda 100644 --- a/library/main/src/com/android/setupwizardlib/template/NavigationBarMixin.java +++ b/library/main/src/com/android/setupwizardlib/template/NavigationBarMixin.java @@ -17,67 +17,60 @@ package com.android.setupwizardlib.template; import android.view.View; - import com.android.setupwizardlib.R; import com.android.setupwizardlib.TemplateLayout; import com.android.setupwizardlib.view.NavigationBar; import com.android.setupwizardlib.view.NavigationBar.NavigationBarListener; -/** - * A {@link Mixin} for interacting with a {@link NavigationBar}. - */ +/** A {@link Mixin} for interacting with a {@link NavigationBar}. */ public class NavigationBarMixin implements Mixin { - private TemplateLayout mTemplateLayout; + private final TemplateLayout templateLayout; - /** - * @param layout The layout this mixin belongs to. - */ - public NavigationBarMixin(TemplateLayout layout) { - mTemplateLayout = layout; - } + /** @param layout The layout this mixin belongs to. */ + public NavigationBarMixin(TemplateLayout layout) { + templateLayout = layout; + } - /** - * @return The navigation bar instance in the layout, or null if the layout does not have a - * navigation bar. - */ - public NavigationBar getNavigationBar() { - final View view = mTemplateLayout.findManagedViewById(R.id.suw_layout_navigation_bar); - return view instanceof NavigationBar ? (NavigationBar) view : null; - } + /** + * @return The navigation bar instance in the layout, or null if the layout does not have a + * navigation bar. + */ + public NavigationBar getNavigationBar() { + final View view = templateLayout.findManagedViewById(R.id.suw_layout_navigation_bar); + return view instanceof NavigationBar ? (NavigationBar) view : null; + } - /** - * Sets the label of the next button. - * - * @param text Label of the next button. - */ - public void setNextButtonText(int text) { - getNavigationBar().getNextButton().setText(text); - } + /** + * Sets the label of the next button. + * + * @param text Label of the next button. + */ + public void setNextButtonText(int text) { + getNavigationBar().getNextButton().setText(text); + } - /** - * Sets the label of the next button. - * - * @param text Label of the next button. - */ - public void setNextButtonText(CharSequence text) { - getNavigationBar().getNextButton().setText(text); - } + /** + * Sets the label of the next button. + * + * @param text Label of the next button. + */ + public void setNextButtonText(CharSequence text) { + getNavigationBar().getNextButton().setText(text); + } - /** - * @return The current label of the next button. - */ - public CharSequence getNextButtonText() { - return getNavigationBar().getNextButton().getText(); - } + /** @return The current label of the next button. */ + public CharSequence getNextButtonText() { + return getNavigationBar().getNextButton().getText(); + } - /** - * Sets the listener to handle back and next button clicks in the navigation bar. - * - * @see NavigationBar#setNavigationBarListener(NavigationBarListener) - * @see NavigationBarListener - */ - public void setNavigationBarListener(NavigationBarListener listener) { - getNavigationBar().setNavigationBarListener(listener); - } + /** + * Sets the listener to handle back and next button clicks in the navigation bar. + * + * @see NavigationBar#setNavigationBarListener(NavigationBarListener) + * @see NavigationBarListener + */ + public void setNavigationBarListener(NavigationBarListener listener) { + getNavigationBar().setNavigationBarListener(listener); + } } diff --git a/library/main/src/com/android/setupwizardlib/template/ProgressBarMixin.java b/library/main/src/com/android/setupwizardlib/template/ProgressBarMixin.java index 504b2f0..0e128c4 100644 --- a/library/main/src/com/android/setupwizardlib/template/ProgressBarMixin.java +++ b/library/main/src/com/android/setupwizardlib/template/ProgressBarMixin.java @@ -19,121 +19,109 @@ package com.android.setupwizardlib.template; import android.content.res.ColorStateList; import android.os.Build; import android.os.Build.VERSION_CODES; +import androidx.annotation.Nullable; import android.view.View; import android.view.ViewStub; import android.widget.ProgressBar; - -import androidx.annotation.Nullable; - import com.android.setupwizardlib.R; import com.android.setupwizardlib.TemplateLayout; -/** - * A {@link Mixin} for showing a progress bar. - */ +/** A {@link Mixin} for showing a progress bar. */ public class ProgressBarMixin implements Mixin { - private TemplateLayout mTemplateLayout; + private final TemplateLayout templateLayout; - @Nullable - private ColorStateList mColor; + @Nullable private ColorStateList color; - /** - * @param layout The layout this mixin belongs to. - */ - public ProgressBarMixin(TemplateLayout layout) { - mTemplateLayout = layout; - } + /** @param layout The layout this mixin belongs to. */ + public ProgressBarMixin(TemplateLayout layout) { + templateLayout = layout; + } - /** - * @return True if the progress bar is currently shown. - */ - public boolean isShown() { - final View progressBar = mTemplateLayout.findManagedViewById(R.id.suw_layout_progress); - return progressBar != null && progressBar.getVisibility() == View.VISIBLE; - } + /** @return True if the progress bar is currently shown. */ + public boolean isShown() { + final View progressBar = templateLayout.findManagedViewById(R.id.suw_layout_progress); + return progressBar != null && progressBar.getVisibility() == View.VISIBLE; + } - /** - * Sets whether the progress bar is shown. If the progress bar has not been inflated from the - * stub, this method will inflate the progress bar. - * - * @param shown True to show the progress bar, false to hide it. - */ - public void setShown(boolean shown) { - if (shown) { - View progressBar = getProgressBar(); - if (progressBar != null) { - progressBar.setVisibility(View.VISIBLE); - } - } else { - View progressBar = peekProgressBar(); - if (progressBar != null) { - progressBar.setVisibility(View.GONE); - } - } + /** + * Sets whether the progress bar is shown. If the progress bar has not been inflated from the + * stub, this method will inflate the progress bar. + * + * @param shown True to show the progress bar, false to hide it. + */ + public void setShown(boolean shown) { + if (shown) { + View progressBar = getProgressBar(); + if (progressBar != null) { + progressBar.setVisibility(View.VISIBLE); + } + } else { + View progressBar = peekProgressBar(); + if (progressBar != null) { + progressBar.setVisibility(View.GONE); + } } + } - /** - * Gets the progress bar in the layout. If the progress bar has not been used before, it will be - * installed (i.e. inflated from its view stub). - * - * @return The progress bar of this layout. May be null only if the template used doesn't have a - * progress bar built-in. - */ - private ProgressBar getProgressBar() { - final View progressBar = peekProgressBar(); - if (progressBar == null) { - final ViewStub progressBarStub = - (ViewStub) mTemplateLayout.findManagedViewById(R.id.suw_layout_progress_stub); - if (progressBarStub != null) { - progressBarStub.inflate(); - } - setColor(mColor); - } - return peekProgressBar(); + /** + * Gets the progress bar in the layout. If the progress bar has not been used before, it will be + * installed (i.e. inflated from its view stub). + * + * @return The progress bar of this layout. May be null only if the template used doesn't have a + * progress bar built-in. + */ + private ProgressBar getProgressBar() { + final View progressBar = peekProgressBar(); + if (progressBar == null) { + final ViewStub progressBarStub = + (ViewStub) templateLayout.findManagedViewById(R.id.suw_layout_progress_stub); + if (progressBarStub != null) { + progressBarStub.inflate(); + } + setColor(color); } + return peekProgressBar(); + } - /** - * Gets the progress bar in the layout only if it has been installed. - * {@link #setShown(boolean)} should be called before this to ensure the progress bar - * is set up correctly. - * - * @return The progress bar of this layout, or null if the progress bar is not installed. The - * null case can happen either if {@link #setShown(boolean)} with true was - * not called before this, or if the template does not contain a progress bar. - */ - public ProgressBar peekProgressBar() { - return (ProgressBar) mTemplateLayout.findManagedViewById(R.id.suw_layout_progress); - } + /** + * Gets the progress bar in the layout only if it has been installed. {@link #setShown(boolean)} + * should be called before this to ensure the progress bar is set up correctly. + * + * @return The progress bar of this layout, or null if the progress bar is not installed. The null + * case can happen either if {@link #setShown(boolean)} with true was not called before this, + * or if the template does not contain a progress bar. + */ + public ProgressBar peekProgressBar() { + return (ProgressBar) templateLayout.findManagedViewById(R.id.suw_layout_progress); + } - /** - * Sets the color of the indeterminate progress bar. This method is a no-op on SDK < 21. - */ - public void setColor(@Nullable ColorStateList color) { - mColor = color; - if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { - final ProgressBar bar = peekProgressBar(); - if (bar != null) { - bar.setIndeterminateTintList(color); - if (Build.VERSION.SDK_INT >= VERSION_CODES.M || color != null) { - // There is a bug in Lollipop where setting the progress tint color to null - // will crash with "java.lang.NullPointerException: Attempt to invoke virtual - // method 'int android.graphics.Paint.getAlpha()' on a null object reference" - // at android.graphics.drawable.NinePatchDrawable.draw(:250) - // The bug doesn't affect ProgressBar on M because it uses ShapeDrawable instead - // of NinePatchDrawable. (commit 6a8253fdc9f4574c28b4beeeed90580ffc93734a) - bar.setProgressBackgroundTintList(color); - } - } + /** Sets the color of the indeterminate progress bar. This method is a no-op on SDK < 21. */ + public void setColor(@Nullable ColorStateList color) { + this.color = color; + if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { + final ProgressBar bar = peekProgressBar(); + if (bar != null) { + bar.setIndeterminateTintList(color); + if (Build.VERSION.SDK_INT >= VERSION_CODES.M || color != null) { + // There is a bug in Lollipop where setting the progress tint color to null + // will crash with "java.lang.NullPointerException: Attempt to invoke virtual + // method 'int android.graphics.Paint.getAlpha()' on a null object reference" + // at android.graphics.drawable.NinePatchDrawable.draw(:250) + // The bug doesn't affect ProgressBar on M because it uses ShapeDrawable instead + // of NinePatchDrawable. (commit 6a8253fdc9f4574c28b4beeeed90580ffc93734a) + bar.setProgressBackgroundTintList(color); } + } } + } - /** - * @return The color previously set in {@link #setColor(ColorStateList)}, or null if the color - * is not set. In case of null, the color of the progress bar will be inherited from the theme. - */ - @Nullable - public ColorStateList getColor() { - return mColor; - } + /** + * @return The color previously set in {@link #setColor(ColorStateList)}, or null if the color is + * not set. In case of null, the color of the progress bar will be inherited from the theme. + */ + @Nullable + public ColorStateList getColor() { + return color; + } } diff --git a/library/main/src/com/android/setupwizardlib/template/RequireScrollMixin.java b/library/main/src/com/android/setupwizardlib/template/RequireScrollMixin.java index fd3303b..02bcc1c 100644 --- a/library/main/src/com/android/setupwizardlib/template/RequireScrollMixin.java +++ b/library/main/src/com/android/setupwizardlib/template/RequireScrollMixin.java @@ -18,244 +18,222 @@ package com.android.setupwizardlib.template; import android.os.Handler; import android.os.Looper; -import android.view.View; -import android.view.View.OnClickListener; -import android.widget.Button; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; - +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; import com.android.setupwizardlib.TemplateLayout; import com.android.setupwizardlib.view.NavigationBar; /** - * A mixin to require the a scrollable container (BottomScrollView, RecyclerView or ListView) to - * be scrolled to bottom, making sure that the user sees all content above and below the fold. + * A mixin to require the a scrollable container (BottomScrollView, RecyclerView or ListView) to be + * scrolled to bottom, making sure that the user sees all content above and below the fold. */ public class RequireScrollMixin implements Mixin { - /* static section */ - - /** - * Listener for when the require-scroll state changes. Note that this only requires the user to - * scroll to the bottom once - if the user scrolled to the bottom and back-up, scrolling to - * bottom is not required again. - */ - public interface OnRequireScrollStateChangedListener { + /* static section */ - /** - * Called when require-scroll state changed. - * - * @param scrollNeeded True if the user should be required to scroll to bottom. - */ - void onRequireScrollStateChanged(boolean scrollNeeded); - } + /** + * Listener for when the require-scroll state changes. Note that this only requires the user to + * scroll to the bottom once - if the user scrolled to the bottom and back-up, scrolling to bottom + * is not required again. + */ + public interface OnRequireScrollStateChangedListener { /** - * A delegate to detect scrollability changes and to scroll the page. This provides a layer - * of abstraction for BottomScrollView, RecyclerView and ListView. The delegate should call - * {@link #notifyScrollabilityChange(boolean)} when the view scrollability is changed. - */ - interface ScrollHandlingDelegate { - - /** - * Starts listening to scrollability changes at the target scrollable container. - */ - void startListening(); - - /** - * Scroll the page content down by one page. - */ - void pageScrollDown(); - } - - /* non-static section */ - - @NonNull - private final TemplateLayout mTemplateLayout; - - private final Handler mHandler = new Handler(Looper.getMainLooper()); - - private boolean mRequiringScrollToBottom = false; - - // Whether the user have seen the more button yet. - private boolean mEverScrolledToBottom = false; - - private ScrollHandlingDelegate mDelegate; - - @Nullable - private OnRequireScrollStateChangedListener mListener; - - /** - * @param templateLayout The template containing this mixin - */ - public RequireScrollMixin(@NonNull TemplateLayout templateLayout) { - mTemplateLayout = templateLayout; - } - - /** - * Sets the delegate to handle scrolling. The type of delegate should depend on whether the - * scrolling view is a BottomScrollView, RecyclerView or ListView. - */ - public void setScrollHandlingDelegate(@NonNull ScrollHandlingDelegate delegate) { - mDelegate = delegate; - } - - /** - * Listen to require scroll state changes. When scroll is required, - * {@link OnRequireScrollStateChangedListener#onRequireScrollStateChanged(boolean)} is called - * with {@code true}, and vice versa. - */ - public void setOnRequireScrollStateChangedListener( - @Nullable OnRequireScrollStateChangedListener listener) { - mListener = listener; - } - - /** - * @return The scroll state listener previously set, or {@code null} if none is registered. - */ - public OnRequireScrollStateChangedListener getOnRequireScrollStateChangedListener() { - return mListener; - } - - /** - * Creates an {@link OnClickListener} which if scrolling is required, will scroll the page down, - * and if scrolling is not required, delegates to the wrapped {@code listener}. Note that you - * should call {@link #requireScroll()} as well in order to start requiring scrolling. + * Called when require-scroll state changed. * - * @param listener The listener to be invoked when scrolling is not needed and the user taps on - * the button. If {@code null}, the click listener will be a no-op when scroll - * is not required. - * @return A new {@link OnClickListener} which will scroll the page down or delegate to the - * given listener depending on the current require-scroll state. - */ - public OnClickListener createOnClickListener(@Nullable final OnClickListener listener) { - return new OnClickListener() { - @Override - public void onClick(View view) { - if (mRequiringScrollToBottom) { - mDelegate.pageScrollDown(); - } else if (listener != null) { - listener.onClick(view); - } - } - }; - } - - /** - * Coordinate with the given navigation bar to require scrolling on the page. The more button - * will be shown instead of the next button while scrolling is required. + * @param scrollNeeded True if the user should be required to scroll to bottom. */ - public void requireScrollWithNavigationBar(@NonNull final NavigationBar navigationBar) { - setOnRequireScrollStateChangedListener( - new OnRequireScrollStateChangedListener() { - @Override - public void onRequireScrollStateChanged(boolean scrollNeeded) { - navigationBar.getMoreButton() - .setVisibility(scrollNeeded ? View.VISIBLE : View.GONE); - navigationBar.getNextButton() - .setVisibility(scrollNeeded ? View.GONE : View.VISIBLE); - } - }); - navigationBar.getMoreButton().setOnClickListener(createOnClickListener(null)); - requireScroll(); - } - - /** - * @see #requireScrollWithButton(Button, CharSequence, OnClickListener) - */ - public void requireScrollWithButton( - @NonNull Button button, - @StringRes int moreText, - @Nullable OnClickListener onClickListener) { - requireScrollWithButton(button, button.getContext().getText(moreText), onClickListener); - } - - /** - * Use the given {@code button} to require scrolling. When scrolling is required, the button - * label will change to {@code moreText}, and tapping the button will cause the page to scroll - * down. - * - * <p>Note: Calling {@link View#setOnClickListener} on the button after this method will remove - * its link to the require-scroll mechanism. If you need to do that, obtain the click listener - * from {@link #createOnClickListener(OnClickListener)}. - * - * <p>Note: The normal button label is taken from the button's text at the time of calling this - * method. Calling {@link android.widget.TextView#setText} after calling this method causes - * undefined behavior. - * - * @param button The button to use for require scroll. The button's "normal" label is taken from - * the text at the time of calling this method, and the click listener of it will - * be replaced. - * @param moreText The button label when scroll is required. - * @param onClickListener The listener for clicks when scrolling is not required. - */ - public void requireScrollWithButton( - @NonNull final Button button, - final CharSequence moreText, - @Nullable OnClickListener onClickListener) { - final CharSequence nextText = button.getText(); - button.setOnClickListener(createOnClickListener(onClickListener)); - setOnRequireScrollStateChangedListener(new OnRequireScrollStateChangedListener() { - @Override - public void onRequireScrollStateChanged(boolean scrollNeeded) { - button.setText(scrollNeeded ? moreText : nextText); - } + void onRequireScrollStateChanged(boolean scrollNeeded); + } + + /** + * A delegate to detect scrollability changes and to scroll the page. This provides a layer of + * abstraction for BottomScrollView, RecyclerView and ListView. The delegate should call {@link + * #notifyScrollabilityChange(boolean)} when the view scrollability is changed. + */ + interface ScrollHandlingDelegate { + + /** Starts listening to scrollability changes at the target scrollable container. */ + void startListening(); + + /** Scroll the page content down by one page. */ + void pageScrollDown(); + } + + /* non-static section */ + + private final Handler handler = new Handler(Looper.getMainLooper()); + + private boolean requiringScrollToBottom = false; + + // Whether the user have seen the more button yet. + private boolean everScrolledToBottom = false; + + private ScrollHandlingDelegate delegate; + + @Nullable private OnRequireScrollStateChangedListener listener; + + /** @param templateLayout The template containing this mixin */ + public RequireScrollMixin(@NonNull TemplateLayout templateLayout) { + } + + /** + * Sets the delegate to handle scrolling. The type of delegate should depend on whether the + * scrolling view is a BottomScrollView, RecyclerView or ListView. + */ + public void setScrollHandlingDelegate(@NonNull ScrollHandlingDelegate delegate) { + this.delegate = delegate; + } + + /** + * Listen to require scroll state changes. When scroll is required, {@link + * OnRequireScrollStateChangedListener#onRequireScrollStateChanged(boolean)} is called with {@code + * true}, and vice versa. + */ + public void setOnRequireScrollStateChangedListener( + @Nullable OnRequireScrollStateChangedListener listener) { + this.listener = listener; + } + + /** @return The scroll state listener previously set, or {@code null} if none is registered. */ + public OnRequireScrollStateChangedListener getOnRequireScrollStateChangedListener() { + return listener; + } + + /** + * Creates an {@link OnClickListener} which if scrolling is required, will scroll the page down, + * and if scrolling is not required, delegates to the wrapped {@code listener}. Note that you + * should call {@link #requireScroll()} as well in order to start requiring scrolling. + * + * @param listener The listener to be invoked when scrolling is not needed and the user taps on + * the button. If {@code null}, the click listener will be a no-op when scroll is not + * required. + * @return A new {@link OnClickListener} which will scroll the page down or delegate to the given + * listener depending on the current require-scroll state. + */ + public OnClickListener createOnClickListener(@Nullable final OnClickListener listener) { + return new OnClickListener() { + @Override + public void onClick(View view) { + if (requiringScrollToBottom) { + delegate.pageScrollDown(); + } else if (listener != null) { + listener.onClick(view); + } + } + }; + } + + /** + * Coordinate with the given navigation bar to require scrolling on the page. The more button will + * be shown instead of the next button while scrolling is required. + */ + public void requireScrollWithNavigationBar(@NonNull final NavigationBar navigationBar) { + setOnRequireScrollStateChangedListener( + new OnRequireScrollStateChangedListener() { + @Override + public void onRequireScrollStateChanged(boolean scrollNeeded) { + navigationBar.getMoreButton().setVisibility(scrollNeeded ? View.VISIBLE : View.GONE); + navigationBar.getNextButton().setVisibility(scrollNeeded ? View.GONE : View.VISIBLE); + } }); - requireScroll(); - } - - /** - * @return True if scrolling is required. Note that this mixin only requires the user to - * scroll to the bottom once - if the user scrolled to the bottom and back-up, scrolling to - * bottom is not required again. - */ - public boolean isScrollingRequired() { - return mRequiringScrollToBottom; + navigationBar.getMoreButton().setOnClickListener(createOnClickListener(null)); + requireScroll(); + } + + /** @see #requireScrollWithButton(Button, CharSequence, OnClickListener) */ + public void requireScrollWithButton( + @NonNull Button button, @StringRes int moreText, @Nullable OnClickListener onClickListener) { + requireScrollWithButton(button, button.getContext().getText(moreText), onClickListener); + } + + /** + * Use the given {@code button} to require scrolling. When scrolling is required, the button label + * will change to {@code moreText}, and tapping the button will cause the page to scroll down. + * + * <p>Note: Calling {@link View#setOnClickListener} on the button after this method will remove + * its link to the require-scroll mechanism. If you need to do that, obtain the click listener + * from {@link #createOnClickListener(OnClickListener)}. + * + * <p>Note: The normal button label is taken from the button's text at the time of calling this + * method. Calling {@link android.widget.TextView#setText} after calling this method causes + * undefined behavior. + * + * @param button The button to use for require scroll. The button's "normal" label is taken from + * the text at the time of calling this method, and the click listener of it will be replaced. + * @param moreText The button label when scroll is required. + * @param onClickListener The listener for clicks when scrolling is not required. + */ + public void requireScrollWithButton( + @NonNull final Button button, + final CharSequence moreText, + @Nullable OnClickListener onClickListener) { + final CharSequence nextText = button.getText(); + button.setOnClickListener(createOnClickListener(onClickListener)); + setOnRequireScrollStateChangedListener( + new OnRequireScrollStateChangedListener() { + @Override + public void onRequireScrollStateChanged(boolean scrollNeeded) { + button.setText(scrollNeeded ? moreText : nextText); + } + }); + requireScroll(); + } + + /** + * @return True if scrolling is required. Note that this mixin only requires the user to scroll to + * the bottom once - if the user scrolled to the bottom and back-up, scrolling to bottom is + * not required again. + */ + public boolean isScrollingRequired() { + return requiringScrollToBottom; + } + + /** + * Start requiring scrolling on the layout. After calling this method, this mixin will start + * listening to scroll events from the scrolling container, and call {@link + * OnRequireScrollStateChangedListener} when the scroll state changes. + */ + public void requireScroll() { + delegate.startListening(); + } + + /** + * {@link ScrollHandlingDelegate} should call this method when the scrollability of the scrolling + * container changed, so this mixin can recompute whether scrolling should be required. + * + * @param canScrollDown True if the view can scroll down further. + */ + void notifyScrollabilityChange(boolean canScrollDown) { + if (canScrollDown == requiringScrollToBottom) { + // Already at the desired require-scroll state + return; } - - /** - * Start requiring scrolling on the layout. After calling this method, this mixin will start - * listening to scroll events from the scrolling container, and call - * {@link OnRequireScrollStateChangedListener} when the scroll state changes. - */ - public void requireScroll() { - mDelegate.startListening(); + if (canScrollDown) { + if (!everScrolledToBottom) { + postScrollStateChange(true); + requiringScrollToBottom = true; + } + } else { + postScrollStateChange(false); + requiringScrollToBottom = false; + everScrolledToBottom = true; } - - /** - * {@link ScrollHandlingDelegate} should call this method when the scrollability of the - * scrolling container changed, so this mixin can recompute whether scrolling should be - * required. - * - * @param canScrollDown True if the view can scroll down further. - */ - void notifyScrollabilityChange(boolean canScrollDown) { - if (canScrollDown == mRequiringScrollToBottom) { - // Already at the desired require-scroll state - return; - } - if (canScrollDown) { - if (!mEverScrolledToBottom) { - postScrollStateChange(true); - mRequiringScrollToBottom = true; - } - } else { - postScrollStateChange(false); - mRequiringScrollToBottom = false; - mEverScrolledToBottom = true; - } - } - - private void postScrollStateChange(final boolean scrollNeeded) { - mHandler.post(new Runnable() { - @Override - public void run() { - if (mListener != null) { - mListener.onRequireScrollStateChanged(scrollNeeded); - } + } + + private void postScrollStateChange(final boolean scrollNeeded) { + handler.post( + new Runnable() { + @Override + public void run() { + if (listener != null) { + listener.onRequireScrollStateChanged(scrollNeeded); } + } }); - } + } } diff --git a/library/main/src/com/android/setupwizardlib/template/ScrollViewScrollHandlingDelegate.java b/library/main/src/com/android/setupwizardlib/template/ScrollViewScrollHandlingDelegate.java index 9e4d1cf..dcaa379 100644 --- a/library/main/src/com/android/setupwizardlib/template/ScrollViewScrollHandlingDelegate.java +++ b/library/main/src/com/android/setupwizardlib/template/ScrollViewScrollHandlingDelegate.java @@ -16,12 +16,10 @@ package com.android.setupwizardlib.template; -import android.util.Log; -import android.widget.ScrollView; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; - +import android.util.Log; +import android.widget.ScrollView; import com.android.setupwizardlib.template.RequireScrollMixin.ScrollHandlingDelegate; import com.android.setupwizardlib.view.BottomScrollView; import com.android.setupwizardlib.view.BottomScrollView.BottomScrollListener; @@ -31,51 +29,48 @@ import com.android.setupwizardlib.view.BottomScrollView.BottomScrollListener; * notifies {@link RequireScrollMixin} about scrollability changes. */ public class ScrollViewScrollHandlingDelegate - implements ScrollHandlingDelegate, BottomScrollListener { + implements ScrollHandlingDelegate, BottomScrollListener { - private static final String TAG = "ScrollViewDelegate"; + private static final String TAG = "ScrollViewDelegate"; - @NonNull - private final RequireScrollMixin mRequireScrollMixin; + @NonNull private final RequireScrollMixin requireScrollMixin; - @Nullable - private final BottomScrollView mScrollView; + @Nullable private final BottomScrollView scrollView; - public ScrollViewScrollHandlingDelegate( - @NonNull RequireScrollMixin requireScrollMixin, - @Nullable ScrollView scrollView) { - mRequireScrollMixin = requireScrollMixin; - if (scrollView instanceof BottomScrollView) { - mScrollView = (BottomScrollView) scrollView; - } else { - Log.w(TAG, "Cannot set non-BottomScrollView. Found=" + scrollView); - mScrollView = null; - } + public ScrollViewScrollHandlingDelegate( + @NonNull RequireScrollMixin requireScrollMixin, @Nullable ScrollView scrollView) { + this.requireScrollMixin = requireScrollMixin; + if (scrollView instanceof BottomScrollView) { + this.scrollView = (BottomScrollView) scrollView; + } else { + Log.w(TAG, "Cannot set non-BottomScrollView. Found=" + scrollView); + this.scrollView = null; } + } - @Override - public void onScrolledToBottom() { - mRequireScrollMixin.notifyScrollabilityChange(false); - } + @Override + public void onScrolledToBottom() { + requireScrollMixin.notifyScrollabilityChange(false); + } - @Override - public void onRequiresScroll() { - mRequireScrollMixin.notifyScrollabilityChange(true); - } + @Override + public void onRequiresScroll() { + requireScrollMixin.notifyScrollabilityChange(true); + } - @Override - public void startListening() { - if (mScrollView != null) { - mScrollView.setBottomScrollListener(this); - } else { - Log.w(TAG, "Cannot require scroll. Scroll view is null."); - } + @Override + public void startListening() { + if (scrollView != null) { + scrollView.setBottomScrollListener(this); + } else { + Log.w(TAG, "Cannot require scroll. Scroll view is null."); } + } - @Override - public void pageScrollDown() { - if (mScrollView != null) { - mScrollView.pageScroll(ScrollView.FOCUS_DOWN); - } + @Override + public void pageScrollDown() { + if (scrollView != null) { + scrollView.pageScroll(ScrollView.FOCUS_DOWN); } + } } diff --git a/library/main/src/com/android/setupwizardlib/util/DrawableLayoutDirectionHelper.java b/library/main/src/com/android/setupwizardlib/util/DrawableLayoutDirectionHelper.java index b0afaba..8214415 100644 --- a/library/main/src/com/android/setupwizardlib/util/DrawableLayoutDirectionHelper.java +++ b/library/main/src/com/android/setupwizardlib/util/DrawableLayoutDirectionHelper.java @@ -23,59 +23,77 @@ import android.graphics.drawable.InsetDrawable; import android.os.Build; import android.view.View; -/** - * Provides convenience methods to handle drawable layout directions in different SDK versions. - */ +/** Provides convenience methods to handle drawable layout directions in different SDK versions. */ public class DrawableLayoutDirectionHelper { - /** - * Creates an {@link android.graphics.drawable.InsetDrawable} according to the layout direction - * of {@code view}. - */ - @SuppressLint("InlinedApi") // Use of View.LAYOUT_DIRECTION_RTL is guarded by version check - public static InsetDrawable createRelativeInsetDrawable(Drawable drawable, - int insetStart, int insetTop, int insetEnd, int insetBottom, View view) { - boolean isRtl = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 - && view.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL; - return createRelativeInsetDrawable(drawable, insetStart, insetTop, insetEnd, insetBottom, - isRtl); - } + /** + * Creates an {@link android.graphics.drawable.InsetDrawable} according to the layout direction of + * {@code view}. + */ + @SuppressLint("InlinedApi") // Use of View.LAYOUT_DIRECTION_RTL is guarded by version check + public static InsetDrawable createRelativeInsetDrawable( + Drawable drawable, int insetStart, int insetTop, int insetEnd, int insetBottom, View view) { + boolean isRtl = + Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 + && view.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL; + return createRelativeInsetDrawable( + drawable, insetStart, insetTop, insetEnd, insetBottom, isRtl); + } - /** - * Creates an {@link android.graphics.drawable.InsetDrawable} according to the layout direction - * of {@code context}. - */ - @SuppressLint("InlinedApi") // Use of View.LAYOUT_DIRECTION_RTL is guarded by version check - public static InsetDrawable createRelativeInsetDrawable(Drawable drawable, - int insetStart, int insetTop, int insetEnd, int insetBottom, Context context) { - boolean isRtl = false; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - final int layoutDirection = - context.getResources().getConfiguration().getLayoutDirection(); - isRtl = layoutDirection == View.LAYOUT_DIRECTION_RTL; - } - return createRelativeInsetDrawable(drawable, insetStart, insetTop, insetEnd, insetBottom, - isRtl); + /** + * Creates an {@link android.graphics.drawable.InsetDrawable} according to the layout direction of + * {@code context}. + */ + @SuppressLint("InlinedApi") // Use of View.LAYOUT_DIRECTION_RTL is guarded by version check + public static InsetDrawable createRelativeInsetDrawable( + Drawable drawable, + int insetStart, + int insetTop, + int insetEnd, + int insetBottom, + Context context) { + boolean isRtl = false; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { + final int layoutDirection = context.getResources().getConfiguration().getLayoutDirection(); + isRtl = layoutDirection == View.LAYOUT_DIRECTION_RTL; } + return createRelativeInsetDrawable( + drawable, insetStart, insetTop, insetEnd, insetBottom, isRtl); + } - /** - * Creates an {@link android.graphics.drawable.InsetDrawable} according to - * {@code layoutDirection}. - */ - @SuppressLint("InlinedApi") // Given layoutDirection will not be View.LAYOUT_DIRECTION_RTL if - // SDK version doesn't support it. - public static InsetDrawable createRelativeInsetDrawable(Drawable drawable, - int insetStart, int insetTop, int insetEnd, int insetBottom, int layoutDirection) { - return createRelativeInsetDrawable(drawable, insetStart, insetTop, insetEnd, insetBottom, - layoutDirection == View.LAYOUT_DIRECTION_RTL); - } + /** + * Creates an {@link android.graphics.drawable.InsetDrawable} according to {@code + * layoutDirection}. + */ + @SuppressLint("InlinedApi") // Given layoutDirection will not be View.LAYOUT_DIRECTION_RTL if + // SDK version doesn't support it. + public static InsetDrawable createRelativeInsetDrawable( + Drawable drawable, + int insetStart, + int insetTop, + int insetEnd, + int insetBottom, + int layoutDirection) { + return createRelativeInsetDrawable( + drawable, + insetStart, + insetTop, + insetEnd, + insetBottom, + layoutDirection == View.LAYOUT_DIRECTION_RTL); + } - private static InsetDrawable createRelativeInsetDrawable(Drawable drawable, - int insetStart, int insetTop, int insetEnd, int insetBottom, boolean isRtl) { - if (isRtl) { - return new InsetDrawable(drawable, insetEnd, insetTop, insetStart, insetBottom); - } else { - return new InsetDrawable(drawable, insetStart, insetTop, insetEnd, insetBottom); - } + private static InsetDrawable createRelativeInsetDrawable( + Drawable drawable, + int insetStart, + int insetTop, + int insetEnd, + int insetBottom, + boolean isRtl) { + if (isRtl) { + return new InsetDrawable(drawable, insetEnd, insetTop, insetStart, insetBottom); + } else { + return new InsetDrawable(drawable, insetStart, insetTop, insetEnd, insetBottom); } + } } diff --git a/library/main/src/com/android/setupwizardlib/util/FallbackThemeWrapper.java b/library/main/src/com/android/setupwizardlib/util/FallbackThemeWrapper.java index 2ec4f84..96f9162 100644 --- a/library/main/src/com/android/setupwizardlib/util/FallbackThemeWrapper.java +++ b/library/main/src/com/android/setupwizardlib/util/FallbackThemeWrapper.java @@ -18,37 +18,33 @@ package com.android.setupwizardlib.util; import android.content.Context; import android.content.res.Resources.Theme; -import android.view.ContextThemeWrapper; - import androidx.annotation.StyleRes; +import android.view.ContextThemeWrapper; /** - * Same as {@link ContextThemeWrapper}, but the base context's theme attributes take precedence - * over the wrapper context's. This is used to provide default values for theme attributes - * referenced in layouts, to remove the risk of crashing the client because of using the wrong - * theme. + * Same as {@link ContextThemeWrapper}, but the base context's theme attributes take precedence over + * the wrapper context's. This is used to provide default values for theme attributes referenced in + * layouts, to remove the risk of crashing the client because of using the wrong theme. */ public class FallbackThemeWrapper extends ContextThemeWrapper { - /** - * Creates a new context wrapper with the specified theme. - * - * The specified theme will be applied as fallbacks to the base context's theme. Any attributes - * defined in the base context's theme will retain their original values. Otherwise values in - * {@code themeResId} will be used. - * - * @param base The base context. - * @param themeResId The theme to use as fallback. - */ - public FallbackThemeWrapper(Context base, @StyleRes int themeResId) { - super(base, themeResId); - } + /** + * Creates a new context wrapper with the specified theme. + * + * <p>The specified theme will be applied as fallbacks to the base context's theme. Any attributes + * defined in the base context's theme will retain their original values. Otherwise values in + * {@code themeResId} will be used. + * + * @param base The base context. + * @param themeResId The theme to use as fallback. + */ + public FallbackThemeWrapper(Context base, @StyleRes int themeResId) { + super(base, themeResId); + } - /** - * {@inheritDoc} - */ - @Override - protected void onApplyThemeResource(Theme theme, int resId, boolean first) { - theme.applyStyle(resId, false /* force */); - } + /** {@inheritDoc} */ + @Override + protected void onApplyThemeResource(Theme theme, int resId, boolean first) { + theme.applyStyle(resId, false /* force */); + } } diff --git a/library/main/src/com/android/setupwizardlib/util/Partner.java b/library/main/src/com/android/setupwizardlib/util/Partner.java index 9eaedc3..ce782cb 100644 --- a/library/main/src/com/android/setupwizardlib/util/Partner.java +++ b/library/main/src/com/android/setupwizardlib/util/Partner.java @@ -26,14 +26,13 @@ import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; -import android.util.Log; - import androidx.annotation.AnyRes; import androidx.annotation.ColorRes; import androidx.annotation.DrawableRes; +import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.annotation.VisibleForTesting; - +import android.util.Log; import java.util.List; /** @@ -46,157 +45,156 @@ import java.util.List; */ public class Partner { - private static final String TAG = "(SUW) Partner"; - - /** Marker action used to discover partner */ - private static final String ACTION_PARTNER_CUSTOMIZATION = - "com.android.setupwizard.action.PARTNER_CUSTOMIZATION"; - - private static boolean sSearched = false; - private static Partner sPartner; - - /** - * Convenience to get a drawable from partner overlay, or if not available, the drawable from - * the original context. - * - * @see #getResourceEntry(android.content.Context, int) - */ - public static Drawable getDrawable(Context context, @DrawableRes int id) { - final ResourceEntry entry = getResourceEntry(context, id); - return entry.resources.getDrawable(entry.id); + private static final String TAG = "(SUW) Partner"; + + /** Marker action used to discover partner. */ + private static final String ACTION_PARTNER_CUSTOMIZATION = + "com.android.setupwizard.action.PARTNER_CUSTOMIZATION"; + + private static boolean searched = false; + @Nullable private static Partner partner; + + /** + * Gets a drawable from partner overlay, or if not available, the drawable from the original + * context. + * + * @see #getResourceEntry(android.content.Context, int) + */ + public static Drawable getDrawable(Context context, @DrawableRes int id) { + final ResourceEntry entry = getResourceEntry(context, id); + return entry.resources.getDrawable(entry.id); + } + + /** + * Gets a string from partner overlay, or if not available, the string from the original context. + * + * @see #getResourceEntry(android.content.Context, int) + */ + public static String getString(Context context, @StringRes int id) { + final ResourceEntry entry = getResourceEntry(context, id); + return entry.resources.getString(entry.id); + } + + /** + * Gets a color from partner overlay, or if not available, the color from the original context. + */ + public static int getColor(Context context, @ColorRes int id) { + final ResourceEntry resourceEntry = getResourceEntry(context, id); + return resourceEntry.resources.getColor(resourceEntry.id); + } + + /** + * Gets a CharSequence from partner overlay, or if not available, the text from the original + * context. + */ + public static CharSequence getText(Context context, @StringRes int id) { + final ResourceEntry entry = getResourceEntry(context, id); + return entry.resources.getText(entry.id); + } + + /** + * Finds an entry of resource in the overlay package provided by partners. It will first look for + * the resource in the overlay package, and if not available, will return the one in the original + * context. + * + * @return a ResourceEntry in the partner overlay's resources, if one is defined. Otherwise the + * resources from the original context is returned. Clients can then get the resource by + * {@code entry.resources.getString(entry.id)}, or other methods available in {@link + * android.content.res.Resources}. + */ + public static ResourceEntry getResourceEntry(Context context, @AnyRes int id) { + final Partner partner = Partner.get(context); + if (partner != null) { + final Resources ourResources = context.getResources(); + final String name = ourResources.getResourceEntryName(id); + final String type = ourResources.getResourceTypeName(id); + final int partnerId = partner.getIdentifier(name, type); + if (partnerId != 0) { + return new ResourceEntry(partner.resources, partnerId, true); + } } - - /** - * Convenience to get a string from partner overlay, or if not available, the string from the - * original context. - * - * @see #getResourceEntry(android.content.Context, int) - */ - public static String getString(Context context, @StringRes int id) { - final ResourceEntry entry = getResourceEntry(context, id); - return entry.resources.getString(entry.id); - } - - /** - * Convenience method to get color from partner overlay, or if not available, the color from - * the original context. - */ - public static int getColor(Context context, @ColorRes int id) { - final ResourceEntry resourceEntry = getResourceEntry(context, id); - return resourceEntry.resources.getColor(resourceEntry.id); - } - - /** - * Convenience method to get a CharSequence from partner overlay, or if not available, the text - * from the original context. - */ - public static CharSequence getText(Context context, @StringRes int id) { - final ResourceEntry entry = getResourceEntry(context, id); - return entry.resources.getText(entry.id); - } - - /** - * Find an entry of resource in the overlay package provided by partners. It will first look for - * the resource in the overlay package, and if not available, will return the one in the - * original context. - * - * @return a ResourceEntry in the partner overlay's resources, if one is defined. Otherwise the - * resources from the original context is returned. Clients can then get the resource by - * {@code entry.resources.getString(entry.id)}, or other methods available in - * {@link android.content.res.Resources}. - */ - public static ResourceEntry getResourceEntry(Context context, @AnyRes int id) { - final Partner partner = Partner.get(context); - if (partner != null) { - final Resources ourResources = context.getResources(); - final String name = ourResources.getResourceEntryName(id); - final String type = ourResources.getResourceTypeName(id); - final int partnerId = partner.getIdentifier(name, type); - if (partnerId != 0) { - return new ResourceEntry(partner.mResources, partnerId, true); - } - } - return new ResourceEntry(context.getResources(), id, false); + return new ResourceEntry(context.getResources(), id, false); + } + + public static class ResourceEntry { + public Resources resources; + public int id; + public boolean isOverlay; + + ResourceEntry(Resources resources, int id, boolean isOverlay) { + this.resources = resources; + this.id = id; + this.isOverlay = isOverlay; } - - public static class ResourceEntry { - public Resources resources; - public int id; - public boolean isOverlay; - - ResourceEntry(Resources resources, int id, boolean isOverlay) { - this.resources = resources; - this.id = id; - this.isOverlay = isOverlay; + } + + /** + * Finds and returns partner details, or {@code null} if none exists. A partner package is marked + * by a broadcast receiver declared in the manifest that handles the {@code + * com.android.setupwizard.action.PARTNER_CUSTOMIZATION} intent action. The overlay package must + * also be a system package. + */ + public static synchronized Partner get(Context context) { + if (!searched) { + PackageManager pm = context.getPackageManager(); + final Intent intent = new Intent(ACTION_PARTNER_CUSTOMIZATION); + List<ResolveInfo> receivers; + if (VERSION.SDK_INT >= VERSION_CODES.N) { + receivers = + pm.queryBroadcastReceivers( + intent, + PackageManager.MATCH_SYSTEM_ONLY + | PackageManager.MATCH_DIRECT_BOOT_AWARE + | PackageManager.MATCH_DIRECT_BOOT_UNAWARE); + } else { + // On versions before N, direct boot doesn't exist. And the MATCH_SYSTEM_ONLY flag + // doesn't exist so we filter for system apps in code below. + receivers = pm.queryBroadcastReceivers(intent, 0); + } + + for (ResolveInfo info : receivers) { + if (info.activityInfo == null) { + continue; } - } - - /** - * Find and return partner details, or {@code null} if none exists. A partner package is marked - * by a broadcast receiver declared in the manifest that handles the - * {@code com.android.setupwizard.action.PARTNER_CUSTOMIZATION} intent action. The overlay - * package must also be a system package. - */ - public static synchronized Partner get(Context context) { - if (!sSearched) { - PackageManager pm = context.getPackageManager(); - final Intent intent = new Intent(ACTION_PARTNER_CUSTOMIZATION); - List<ResolveInfo> receivers; - if (VERSION.SDK_INT >= VERSION_CODES.N) { - receivers = pm.queryBroadcastReceivers( - intent, - PackageManager.MATCH_SYSTEM_ONLY - | PackageManager.MATCH_DIRECT_BOOT_AWARE - | PackageManager.MATCH_DIRECT_BOOT_UNAWARE); - } else { - // On versions before N, direct boot doesn't exist. And the MATCH_SYSTEM_ONLY flag - // doesn't exist so we filter for system apps in code below. - receivers = pm.queryBroadcastReceivers(intent, 0); - } - - for (ResolveInfo info : receivers) { - if (info.activityInfo == null) { - continue; - } - final ApplicationInfo appInfo = info.activityInfo.applicationInfo; - if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { - try { - final Resources res = pm.getResourcesForApplication(appInfo); - sPartner = new Partner(appInfo.packageName, res); - break; - } catch (NameNotFoundException e) { - Log.w(TAG, "Failed to find resources for " + appInfo.packageName); - } - } - } - sSearched = true; + final ApplicationInfo appInfo = info.activityInfo.applicationInfo; + if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { + try { + final Resources res = pm.getResourcesForApplication(appInfo); + partner = new Partner(appInfo.packageName, res); + break; + } catch (NameNotFoundException e) { + Log.w(TAG, "Failed to find resources for " + appInfo.packageName); + } } - return sPartner; - } - - @VisibleForTesting - public static synchronized void resetForTesting() { - sSearched = false; - sPartner = null; - } - - private final String mPackageName; - private final Resources mResources; - - private Partner(String packageName, Resources res) { - mPackageName = packageName; - mResources = res; - } - - public String getPackageName() { - return mPackageName; - } - - public Resources getResources() { - return mResources; - } - - public int getIdentifier(String name, String defType) { - return mResources.getIdentifier(name, defType, mPackageName); + } + searched = true; } + return partner; + } + + @VisibleForTesting + public static synchronized void resetForTesting() { + searched = false; + partner = null; + } + + private final String packageName; + private final Resources resources; + + private Partner(String packageName, Resources res) { + this.packageName = packageName; + resources = res; + } + + public String getPackageName() { + return packageName; + } + + public Resources getResources() { + return resources; + } + + public int getIdentifier(String name, String defType) { + return resources.getIdentifier(name, defType, packageName); + } } diff --git a/library/main/src/com/android/setupwizardlib/util/ResultCodes.java b/library/main/src/com/android/setupwizardlib/util/ResultCodes.java index a429e73..ea20139 100644 --- a/library/main/src/com/android/setupwizardlib/util/ResultCodes.java +++ b/library/main/src/com/android/setupwizardlib/util/ResultCodes.java @@ -20,9 +20,9 @@ import static android.app.Activity.RESULT_FIRST_USER; public final class ResultCodes { - public static final int RESULT_SKIP = RESULT_FIRST_USER; - public static final int RESULT_RETRY = RESULT_FIRST_USER + 1; - public static final int RESULT_ACTIVITY_NOT_FOUND = RESULT_FIRST_USER + 2; + public static final int RESULT_SKIP = RESULT_FIRST_USER; + public static final int RESULT_RETRY = RESULT_FIRST_USER + 1; + public static final int RESULT_ACTIVITY_NOT_FOUND = RESULT_FIRST_USER + 2; - public static final int RESULT_FIRST_SETUP_USER = RESULT_FIRST_USER + 100; + public static final int RESULT_FIRST_SETUP_USER = RESULT_FIRST_USER + 100; } diff --git a/library/main/src/com/android/setupwizardlib/util/SystemBarHelper.java b/library/main/src/com/android/setupwizardlib/util/SystemBarHelper.java index 7e3e885..42350cc 100644 --- a/library/main/src/com/android/setupwizardlib/util/SystemBarHelper.java +++ b/library/main/src/com/android/setupwizardlib/util/SystemBarHelper.java @@ -24,6 +24,7 @@ import android.content.res.TypedArray; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Handler; +import androidx.annotation.RequiresPermission; import android.util.Log; import android.view.View; import android.view.ViewGroup; @@ -31,331 +32,327 @@ import android.view.Window; import android.view.WindowInsets; import android.view.WindowManager; -import androidx.annotation.RequiresPermission; - /** * A helper class to manage the system navigation bar and status bar. This will add various * systemUiVisibility flags to the given Window or View to make them follow the Setup Wizard style. * - * When the useImmersiveMode intent extra is true, a screen in Setup Wizard should hide the system - * bars using methods from this class. For Lollipop, {@link #hideSystemBars(android.view.Window)} - * will completely hide the system navigation bar and change the status bar to transparent, and - * layout the screen contents (usually the illustration) behind it. + * <p>When the useImmersiveMode intent extra is true, a screen in Setup Wizard should hide the + * system bars using methods from this class. For Lollipop, {@link + * #hideSystemBars(android.view.Window)} will completely hide the system navigation bar and change + * the status bar to transparent, and layout the screen contents (usually the illustration) behind + * it. */ public class SystemBarHelper { - private static final String TAG = "SystemBarHelper"; - - @SuppressLint("InlinedApi") - private static final int DEFAULT_IMMERSIVE_FLAGS = - View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; - - @SuppressLint("InlinedApi") - private static final int DIALOG_IMMERSIVE_FLAGS = - View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; - - /** - * Needs to be equal to View.STATUS_BAR_DISABLE_BACK - */ - private static final int STATUS_BAR_DISABLE_BACK = 0x00400000; - - /** - * The maximum number of retries when peeking the decor view. When polling for the decor view, - * waiting it to be installed, set a maximum number of retries. - */ - private static final int PEEK_DECOR_VIEW_RETRIES = 3; - - /** - * Hide the navigation bar for a dialog. - * - * <p>This will only take effect in versions Lollipop or above. Otherwise this is a no-op. - */ - public static void hideSystemBars(final Dialog dialog) { - if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { - final Window window = dialog.getWindow(); - temporarilyDisableDialogFocus(window); - addVisibilityFlag(window, DIALOG_IMMERSIVE_FLAGS); - addImmersiveFlagsToDecorView(window, DIALOG_IMMERSIVE_FLAGS); - - // Also set the navigation bar and status bar to transparent color. Note that this - // doesn't work if android.R.boolean.config_enableTranslucentDecor is false. - window.setNavigationBarColor(0); - window.setStatusBarColor(0); - } + private static final String TAG = "SystemBarHelper"; + + @SuppressLint("InlinedApi") + private static final int DEFAULT_IMMERSIVE_FLAGS = + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; + + @SuppressLint("InlinedApi") + private static final int DIALOG_IMMERSIVE_FLAGS = + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; + + /** Needs to be equal to View.STATUS_BAR_DISABLE_BACK */ + private static final int STATUS_BAR_DISABLE_BACK = 0x00400000; + + /** + * The maximum number of retries when peeking the decor view. When polling for the decor view, + * waiting it to be installed, set a maximum number of retries. + */ + private static final int PEEK_DECOR_VIEW_RETRIES = 3; + + /** + * Hide the navigation bar for a dialog. + * + * <p>This will only take effect in versions Lollipop or above. Otherwise this is a no-op. + */ + public static void hideSystemBars(final Dialog dialog) { + if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { + final Window window = dialog.getWindow(); + temporarilyDisableDialogFocus(window); + addVisibilityFlag(window, DIALOG_IMMERSIVE_FLAGS); + addImmersiveFlagsToDecorView(window, DIALOG_IMMERSIVE_FLAGS); + + // Also set the navigation bar and status bar to transparent color. Note that this + // doesn't work if android.R.boolean.config_enableTranslucentDecor is false. + window.setNavigationBarColor(0); + window.setStatusBarColor(0); } - - /** - * Hide the navigation bar, make the color of the status and navigation bars transparent, and - * specify {@link View#SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} flag so that the content is laid-out - * behind the transparent status bar. This is commonly used with - * {@link android.app.Activity#getWindow()} to make the navigation and status bars follow the - * Setup Wizard style. - * - * <p>This will only take effect in versions Lollipop or above. Otherwise this is a no-op. - */ - public static void hideSystemBars(final Window window) { - if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { - addVisibilityFlag(window, DEFAULT_IMMERSIVE_FLAGS); - addImmersiveFlagsToDecorView(window, DEFAULT_IMMERSIVE_FLAGS); - - // Also set the navigation bar and status bar to transparent color. Note that this - // doesn't work if android.R.boolean.config_enableTranslucentDecor is false. - window.setNavigationBarColor(0); - window.setStatusBarColor(0); - } + } + + /** + * Hide the navigation bar, make the color of the status and navigation bars transparent, and + * specify {@link View#SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} flag so that the content is laid-out + * behind the transparent status bar. This is commonly used with {@link + * android.app.Activity#getWindow()} to make the navigation and status bars follow the Setup + * Wizard style. + * + * <p>This will only take effect in versions Lollipop or above. Otherwise this is a no-op. + */ + public static void hideSystemBars(final Window window) { + if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { + addVisibilityFlag(window, DEFAULT_IMMERSIVE_FLAGS); + addImmersiveFlagsToDecorView(window, DEFAULT_IMMERSIVE_FLAGS); + + // Also set the navigation bar and status bar to transparent color. Note that this + // doesn't work if android.R.boolean.config_enableTranslucentDecor is false. + window.setNavigationBarColor(0); + window.setStatusBarColor(0); } - - /** - * Revert the actions of hideSystemBars. Note that this will remove the system UI visibility - * flags regardless of whether it is originally present. You should also manually reset the - * navigation bar and status bar colors, as this method doesn't know what value to revert it to. - */ - public static void showSystemBars(final Dialog dialog, final Context context) { - showSystemBars(dialog.getWindow(), context); + } + + /** + * Revert the actions of hideSystemBars. Note that this will remove the system UI visibility flags + * regardless of whether it is originally present. You should also manually reset the navigation + * bar and status bar colors, as this method doesn't know what value to revert it to. + */ + public static void showSystemBars(final Dialog dialog, final Context context) { + showSystemBars(dialog.getWindow(), context); + } + + /** + * Revert the actions of hideSystemBars. Note that this will remove the system UI visibility flags + * regardless of whether it is originally present. You should also manually reset the navigation + * bar and status bar colors, as this method doesn't know what value to revert it to. + */ + public static void showSystemBars(final Window window, final Context context) { + if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { + removeVisibilityFlag(window, DEFAULT_IMMERSIVE_FLAGS); + removeImmersiveFlagsFromDecorView(window, DEFAULT_IMMERSIVE_FLAGS); + + if (context != null) { + //noinspection AndroidLintInlinedApi + final TypedArray typedArray = + context.obtainStyledAttributes( + new int[] {android.R.attr.statusBarColor, android.R.attr.navigationBarColor}); + final int statusBarColor = typedArray.getColor(0, 0); + final int navigationBarColor = typedArray.getColor(1, 0); + window.setStatusBarColor(statusBarColor); + window.setNavigationBarColor(navigationBarColor); + typedArray.recycle(); + } } + } - /** - * Revert the actions of hideSystemBars. Note that this will remove the system UI visibility - * flags regardless of whether it is originally present. You should also manually reset the - * navigation bar and status bar colors, as this method doesn't know what value to revert it to. - */ - public static void showSystemBars(final Window window, final Context context) { - if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { - removeVisibilityFlag(window, DEFAULT_IMMERSIVE_FLAGS); - removeImmersiveFlagsFromDecorView(window, DEFAULT_IMMERSIVE_FLAGS); - - if (context != null) { - //noinspection AndroidLintInlinedApi - final TypedArray typedArray = context.obtainStyledAttributes(new int[]{ - android.R.attr.statusBarColor, android.R.attr.navigationBarColor}); - final int statusBarColor = typedArray.getColor(0, 0); - final int navigationBarColor = typedArray.getColor(1, 0); - window.setStatusBarColor(statusBarColor); - window.setNavigationBarColor(navigationBarColor); - typedArray.recycle(); - } - } + /** Convenience method to add a visibility flag in addition to the existing ones. */ + public static void addVisibilityFlag(final View view, final int flag) { + if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { + final int vis = view.getSystemUiVisibility(); + view.setSystemUiVisibility(vis | flag); } - - /** - * Convenience method to add a visibility flag in addition to the existing ones. - */ - public static void addVisibilityFlag(final View view, final int flag) { - if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { - final int vis = view.getSystemUiVisibility(); - view.setSystemUiVisibility(vis | flag); - } + } + + /** Convenience method to add a visibility flag in addition to the existing ones. */ + public static void addVisibilityFlag(final Window window, final int flag) { + if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { + WindowManager.LayoutParams attrs = window.getAttributes(); + attrs.systemUiVisibility |= flag; + window.setAttributes(attrs); } - - /** - * Convenience method to add a visibility flag in addition to the existing ones. - */ - public static void addVisibilityFlag(final Window window, final int flag) { - if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { - WindowManager.LayoutParams attrs = window.getAttributes(); - attrs.systemUiVisibility |= flag; - window.setAttributes(attrs); - } + } + + /** + * Convenience method to remove a visibility flag from the view, leaving other flags that are not + * specified intact. + */ + public static void removeVisibilityFlag(final View view, final int flag) { + if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { + final int vis = view.getSystemUiVisibility(); + view.setSystemUiVisibility(vis & ~flag); } - - /** - * Convenience method to remove a visibility flag from the view, leaving other flags that are - * not specified intact. - */ - public static void removeVisibilityFlag(final View view, final int flag) { - if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { - final int vis = view.getSystemUiVisibility(); - view.setSystemUiVisibility(vis & ~flag); - } + } + + /** + * Convenience method to remove a visibility flag from the window, leaving other flags that are + * not specified intact. + */ + public static void removeVisibilityFlag(final Window window, final int flag) { + if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { + WindowManager.LayoutParams attrs = window.getAttributes(); + attrs.systemUiVisibility &= ~flag; + window.setAttributes(attrs); } - - /** - * Convenience method to remove a visibility flag from the window, leaving other flags that are - * not specified intact. - */ - public static void removeVisibilityFlag(final Window window, final int flag) { - if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { - WindowManager.LayoutParams attrs = window.getAttributes(); - attrs.systemUiVisibility &= ~flag; - window.setAttributes(attrs); - } + } + + /** + * Sets whether the back button on the software navigation bar is visible. This only works if you + * have the STATUS_BAR permission. Otherwise framework will filter out this flag and this method + * call will not have any effect. + * + * <p>IMPORTANT: Do not assume that users have no way to go back when the back button is hidden. + * Many devices have physical back buttons, and accessibility services like TalkBack may have + * gestures mapped to back. Please use onBackPressed, onKeyDown, or other similar ways to make + * sure back button events are still handled (or ignored) properly. + */ + @RequiresPermission("android.permission.STATUS_BAR") + public static void setBackButtonVisible(final Window window, final boolean visible) { + if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { + if (visible) { + removeVisibilityFlag(window, STATUS_BAR_DISABLE_BACK); + removeImmersiveFlagsFromDecorView(window, STATUS_BAR_DISABLE_BACK); + } else { + addVisibilityFlag(window, STATUS_BAR_DISABLE_BACK); + addImmersiveFlagsToDecorView(window, STATUS_BAR_DISABLE_BACK); + } } - - /** - * Sets whether the back button on the software navigation bar is visible. This only works if - * you have the STATUS_BAR permission. Otherwise framework will filter out this flag and this - * method call will not have any effect. - * - * <p>IMPORTANT: Do not assume that users have no way to go back when the back button is hidden. - * Many devices have physical back buttons, and accessibility services like TalkBack may have - * gestures mapped to back. Please use onBackPressed, onKeyDown, or other similar ways to - * make sure back button events are still handled (or ignored) properly. - */ - @RequiresPermission("android.permission.STATUS_BAR") - public static void setBackButtonVisible(final Window window, final boolean visible) { - if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { - if (visible) { - removeVisibilityFlag(window, STATUS_BAR_DISABLE_BACK); - removeImmersiveFlagsFromDecorView(window, STATUS_BAR_DISABLE_BACK); - } else { - addVisibilityFlag(window, STATUS_BAR_DISABLE_BACK); - addImmersiveFlagsToDecorView(window, STATUS_BAR_DISABLE_BACK); - } - } + } + + /** + * Set a view to be resized when the keyboard is shown. This will set the bottom margin of the + * view to be immediately above the keyboard, and assumes that the view sits immediately above the + * navigation bar. + * + * <p>Note that you must set {@link android.R.attr#windowSoftInputMode} to {@code adjustResize} + * for this class to work. Otherwise window insets are not dispatched and this method will have no + * effect. + * + * <p>This will only take effect in versions Lollipop or above. Otherwise this is a no-op. + * + * @param view The view to be resized when the keyboard is shown. + */ + public static void setImeInsetView(final View view) { + if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { + view.setOnApplyWindowInsetsListener(new WindowInsetsListener()); } - - /** - * Set a view to be resized when the keyboard is shown. This will set the bottom margin of the - * view to be immediately above the keyboard, and assumes that the view sits immediately above - * the navigation bar. - * - * <p>Note that you must set {@link android.R.attr#windowSoftInputMode} to {@code adjustResize} - * for this class to work. Otherwise window insets are not dispatched and this method will have - * no effect. - * - * <p>This will only take effect in versions Lollipop or above. Otherwise this is a no-op. - * - * @param view The view to be resized when the keyboard is shown. - */ - public static void setImeInsetView(final View view) { - if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { - view.setOnApplyWindowInsetsListener(new WindowInsetsListener()); - } - } - - /** - * Add the specified immersive flags to the decor view of the window, because - * {@link View#SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} only takes effect when it is added to a view - * instead of the window. - */ - @TargetApi(VERSION_CODES.HONEYCOMB) - private static void addImmersiveFlagsToDecorView(final Window window, final int vis) { - getDecorView(window, new OnDecorViewInstalledListener() { - @Override - public void onDecorViewInstalled(View decorView) { - addVisibilityFlag(decorView, vis); - } + } + + /** + * Add the specified immersive flags to the decor view of the window, because {@link + * View#SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} only takes effect when it is added to a view instead of + * the window. + */ + @TargetApi(VERSION_CODES.HONEYCOMB) + private static void addImmersiveFlagsToDecorView(final Window window, final int vis) { + getDecorView( + window, + new OnDecorViewInstalledListener() { + @Override + public void onDecorViewInstalled(View decorView) { + addVisibilityFlag(decorView, vis); + } }); - } - - @TargetApi(VERSION_CODES.HONEYCOMB) - private static void removeImmersiveFlagsFromDecorView(final Window window, final int vis) { - getDecorView(window, new OnDecorViewInstalledListener() { - @Override - public void onDecorViewInstalled(View decorView) { - removeVisibilityFlag(decorView, vis); - } + } + + @TargetApi(VERSION_CODES.HONEYCOMB) + private static void removeImmersiveFlagsFromDecorView(final Window window, final int vis) { + getDecorView( + window, + new OnDecorViewInstalledListener() { + @Override + public void onDecorViewInstalled(View decorView) { + removeVisibilityFlag(decorView, vis); + } }); - } - - private static void getDecorView(Window window, OnDecorViewInstalledListener callback) { - new DecorViewFinder().getDecorView(window, callback, PEEK_DECOR_VIEW_RETRIES); - } - - private static class DecorViewFinder { - - private final Handler mHandler = new Handler(); - private Window mWindow; - private int mRetries; - private OnDecorViewInstalledListener mCallback; - - private Runnable mCheckDecorViewRunnable = new Runnable() { - @Override - public void run() { - // Use peekDecorView instead of getDecorView so that clients can still set window - // features after calling this method. - final View decorView = mWindow.peekDecorView(); - if (decorView != null) { - mCallback.onDecorViewInstalled(decorView); - } else { - mRetries--; - if (mRetries >= 0) { - // If the decor view is not installed yet, try again in the next loop. - mHandler.post(mCheckDecorViewRunnable); - } else { - Log.w(TAG, "Cannot get decor view of window: " + mWindow); - } - } + } + + private static void getDecorView(Window window, OnDecorViewInstalledListener callback) { + new DecorViewFinder().getDecorView(window, callback, PEEK_DECOR_VIEW_RETRIES); + } + + private static class DecorViewFinder { + + private final Handler handler = new Handler(); + private Window window; + private int retries; + private OnDecorViewInstalledListener callback; + + private final Runnable checkDecorViewRunnable = + new Runnable() { + @Override + public void run() { + // Use peekDecorView instead of getDecorView so that clients can still set window + // features after calling this method. + final View decorView = window.peekDecorView(); + if (decorView != null) { + callback.onDecorViewInstalled(decorView); + } else { + retries--; + if (retries >= 0) { + // If the decor view is not installed yet, try again in the next loop. + handler.post(checkDecorViewRunnable); + } else { + Log.w(TAG, "Cannot get decor view of window: " + window); + } } + } }; - public void getDecorView(Window window, OnDecorViewInstalledListener callback, - int retries) { - mWindow = window; - mRetries = retries; - mCallback = callback; - mCheckDecorViewRunnable.run(); - } + public void getDecorView(Window window, OnDecorViewInstalledListener callback, int retries) { + this.window = window; + this.retries = retries; + this.callback = callback; + checkDecorViewRunnable.run(); } - - private interface OnDecorViewInstalledListener { - - void onDecorViewInstalled(View decorView); - } - - /** - * Apply a hack to temporarily set the window to not focusable, so that the navigation bar - * will not show up during the transition. - */ - private static void temporarilyDisableDialogFocus(final Window window) { - window.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, - WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); - // Add the SOFT_INPUT_IS_FORWARD_NAVIGATION_FLAG. This is normally done by the system when - // FLAG_NOT_FOCUSABLE is not set. Setting this flag allows IME to be shown automatically - // if the dialog has editable text fields. - window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION); - new Handler().post(new Runnable() { - @Override - public void run() { + } + + private interface OnDecorViewInstalledListener { + + void onDecorViewInstalled(View decorView); + } + + /** + * Apply a hack to temporarily set the window to not focusable, so that the navigation bar will + * not show up during the transition. + */ + private static void temporarilyDisableDialogFocus(final Window window) { + window.setFlags( + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); + // Add the SOFT_INPUT_IS_FORWARD_NAVIGATION_FLAG. This is normally done by the system when + // FLAG_NOT_FOCUSABLE is not set. Setting this flag allows IME to be shown automatically + // if the dialog has editable text fields. + window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION); + new Handler() + .post( + new Runnable() { + @Override + public void run() { window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); - } - }); + } + }); + } + + @TargetApi(VERSION_CODES.LOLLIPOP) + private static class WindowInsetsListener implements View.OnApplyWindowInsetsListener { + private int bottomOffset; + private boolean hasCalculatedBottomOffset = false; + + @Override + public WindowInsets onApplyWindowInsets(View view, WindowInsets insets) { + if (!hasCalculatedBottomOffset) { + bottomOffset = getBottomDistance(view); + hasCalculatedBottomOffset = true; + } + + int bottomInset = insets.getSystemWindowInsetBottom(); + + final int bottomMargin = Math.max(insets.getSystemWindowInsetBottom() - bottomOffset, 0); + + final ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); + // Check that we have enough space to apply the bottom margins before applying it. + // Otherwise the framework may think that the view is empty and exclude it from layout. + if (bottomMargin < lp.bottomMargin + view.getHeight()) { + lp.setMargins(lp.leftMargin, lp.topMargin, lp.rightMargin, bottomMargin); + view.setLayoutParams(lp); + bottomInset = 0; + } + + return insets.replaceSystemWindowInsets( + insets.getSystemWindowInsetLeft(), + insets.getSystemWindowInsetTop(), + insets.getSystemWindowInsetRight(), + bottomInset); } + } - @TargetApi(VERSION_CODES.LOLLIPOP) - private static class WindowInsetsListener implements View.OnApplyWindowInsetsListener { - private int mBottomOffset; - private boolean mHasCalculatedBottomOffset = false; - - @Override - public WindowInsets onApplyWindowInsets(View view, WindowInsets insets) { - if (!mHasCalculatedBottomOffset) { - mBottomOffset = getBottomDistance(view); - mHasCalculatedBottomOffset = true; - } - - int bottomInset = insets.getSystemWindowInsetBottom(); - - final int bottomMargin = Math.max( - insets.getSystemWindowInsetBottom() - mBottomOffset, 0); - - final ViewGroup.MarginLayoutParams lp = - (ViewGroup.MarginLayoutParams) view.getLayoutParams(); - // Check that we have enough space to apply the bottom margins before applying it. - // Otherwise the framework may think that the view is empty and exclude it from layout. - if (bottomMargin < lp.bottomMargin + view.getHeight()) { - lp.setMargins(lp.leftMargin, lp.topMargin, lp.rightMargin, bottomMargin); - view.setLayoutParams(lp); - bottomInset = 0; - } - - - return insets.replaceSystemWindowInsets( - insets.getSystemWindowInsetLeft(), - insets.getSystemWindowInsetTop(), - insets.getSystemWindowInsetRight(), - bottomInset - ); - } - } - - private static int getBottomDistance(View view) { - int[] coords = new int[2]; - view.getLocationInWindow(coords); - return view.getRootView().getHeight() - coords[1] - view.getHeight(); - } + private static int getBottomDistance(View view) { + int[] coords = new int[2]; + view.getLocationInWindow(coords); + return view.getRootView().getHeight() - coords[1] - view.getHeight(); + } } diff --git a/library/main/src/com/android/setupwizardlib/util/ThemeResolver.java b/library/main/src/com/android/setupwizardlib/util/ThemeResolver.java new file mode 100644 index 0000000..14fdc85 --- /dev/null +++ b/library/main/src/com/android/setupwizardlib/util/ThemeResolver.java @@ -0,0 +1,219 @@ +package com.android.setupwizardlib.util; + +import android.app.Activity; +import android.content.Intent; +import androidx.annotation.Nullable; +import androidx.annotation.StyleRes; +import com.android.setupwizardlib.R; + +/** + * A resolver to resolve the theme from a string or an activity intent, setting options like the + * default theme and the oldest supported theme. Apps can share the resolver across the entire + * process by calling {@link #setDefault(ThemeResolver)} in {@link + * android.app.Application#onCreate()}. If an app needs more granular sharing of the theme default + * values, additional instances of {@link ThemeResolver} can be created using the builder. + */ +public class ThemeResolver { + @StyleRes private final int defaultTheme; + @Nullable private final String oldestSupportedTheme; + private final boolean useDayNight; + + @Nullable private static ThemeResolver defaultResolver; + + /** + * Sets the default instance used for the whole process. Can be null to reset the default to the + * preset one. + */ + public static void setDefault(@Nullable ThemeResolver resolver) { + defaultResolver = resolver; + } + + /** + * Returns the default instance, which can be changed using {@link #setDefault(ThemeResolver)}. + */ + public static ThemeResolver getDefault() { + if (defaultResolver == null) { + defaultResolver = + new ThemeResolver.Builder() + .setDefaultTheme(R.style.SuwThemeGlif_DayNight) + .setUseDayNight(true) + .build(); + } + return defaultResolver; + } + + private ThemeResolver( + int defaultTheme, @Nullable String oldestSupportedTheme, boolean useDayNight) { + this.defaultTheme = defaultTheme; + this.oldestSupportedTheme = oldestSupportedTheme; + this.useDayNight = useDayNight; + } + + /** + * Returns the style for the theme specified in the intent extra. If the specified string theme is + * older than the oldest supported theme, the default will be returned instead. Note that the + * default theme is returned without processing -- it may not be a DayNight theme even if {@link + * #useDayNight} is true. + */ + @StyleRes + public int resolve(Intent intent) { + return resolve( + intent.getStringExtra(WizardManagerHelper.EXTRA_THEME), + /* suppressDayNight= */ WizardManagerHelper.isSetupWizardIntent(intent)); + } + + /** + * Returns the style for the given string theme. If the specified string theme is older than the + * oldest supported theme, the default will be returned instead. Note that the default theme is + * returned without processing -- it may not be a DayNight theme even if {@link #useDayNight} is + * true. + */ + @StyleRes + public int resolve(@Nullable String theme) { + return resolve(theme, /* suppressDayNight= */ false); + } + + @StyleRes + private int resolve(@Nullable String theme, boolean suppressDayNight) { + int themeResource = + useDayNight && !suppressDayNight ? getDayNightThemeRes(theme) : getThemeRes(theme); + if (themeResource == 0) { + return defaultTheme; + } + + if (oldestSupportedTheme != null && compareThemes(theme, oldestSupportedTheme) < 0) { + return defaultTheme; + } + return themeResource; + } + + /** Reads the theme from the intent, and applies the resolved theme to the activity. */ + public void applyTheme(Activity activity) { + activity.setTheme(resolve(activity.getIntent())); + } + + /** + * Returns the corresponding DayNight theme resource ID for the given string theme. DayNight + * themes are themes that will be either light or dark depending on the system setting. For + * example, the string {@link WizardManagerHelper#THEME_GLIF_LIGHT} will return + * {@code @style/SuwThemeGlif.DayNight}. + */ + @StyleRes + private static int getDayNightThemeRes(@Nullable String theme) { + if (theme != null) { + switch (theme) { + case WizardManagerHelper.THEME_GLIF_V3_LIGHT: + case WizardManagerHelper.THEME_GLIF_V3: + return R.style.SuwThemeGlifV3_DayNight; + case WizardManagerHelper.THEME_GLIF_V2_LIGHT: + case WizardManagerHelper.THEME_GLIF_V2: + return R.style.SuwThemeGlifV2_DayNight; + case WizardManagerHelper.THEME_GLIF_LIGHT: + case WizardManagerHelper.THEME_GLIF: + return R.style.SuwThemeGlif_DayNight; + case WizardManagerHelper.THEME_MATERIAL_LIGHT: + case WizardManagerHelper.THEME_MATERIAL: + return R.style.SuwThemeMaterial_DayNight; + default: + // fall through + } + } + return 0; + } + + /** + * Returns the theme resource ID for the given string theme. For example, the string {@link + * WizardManagerHelper#THEME_GLIF_LIGHT} will return {@code @style/SuwThemeGlif.Light}. + */ + @StyleRes + private static int getThemeRes(@Nullable String theme) { + if (theme != null) { + switch (theme) { + case WizardManagerHelper.THEME_GLIF_V3_LIGHT: + return R.style.SuwThemeGlifV3_Light; + case WizardManagerHelper.THEME_GLIF_V3: + return R.style.SuwThemeGlifV3; + case WizardManagerHelper.THEME_GLIF_V2_LIGHT: + return R.style.SuwThemeGlifV2_Light; + case WizardManagerHelper.THEME_GLIF_V2: + return R.style.SuwThemeGlifV2; + case WizardManagerHelper.THEME_GLIF_LIGHT: + return R.style.SuwThemeGlif_Light; + case WizardManagerHelper.THEME_GLIF: + return R.style.SuwThemeGlif; + case WizardManagerHelper.THEME_MATERIAL_LIGHT: + return R.style.SuwThemeMaterial_Light; + case WizardManagerHelper.THEME_MATERIAL: + return R.style.SuwThemeMaterial; + default: + // fall through + } + } + return 0; + } + + /** Compares whether the versions of {@code theme1} and {@code theme2} to check which is newer. */ + private static int compareThemes(String theme1, String theme2) { + return Integer.valueOf(getThemeVersion(theme1)).compareTo(getThemeVersion(theme2)); + } + + /** + * Returns the version of the theme. The absolute number of the theme version is not defined, but + * a larger number in the version indicates a newer theme. + */ + private static int getThemeVersion(String theme) { + if (theme != null) { + switch (theme) { + case WizardManagerHelper.THEME_GLIF_V3_LIGHT: + case WizardManagerHelper.THEME_GLIF_V3: + return 4; + case WizardManagerHelper.THEME_GLIF_V2_LIGHT: + case WizardManagerHelper.THEME_GLIF_V2: + return 3; + case WizardManagerHelper.THEME_GLIF_LIGHT: + case WizardManagerHelper.THEME_GLIF: + return 2; + case WizardManagerHelper.THEME_MATERIAL_LIGHT: + case WizardManagerHelper.THEME_MATERIAL: + return 1; + default: + // fall through + } + } + return -1; + } + + /** Builder class for {@link ThemeResolver}. */ + public static class Builder { + @StyleRes private int defaultTheme = R.style.SuwThemeGlif_DayNight; + @Nullable private String oldestSupportedTheme = null; + private boolean useDayNight = true; + + public Builder() {} + + public Builder(ThemeResolver themeResolver) { + this.defaultTheme = themeResolver.defaultTheme; + this.oldestSupportedTheme = themeResolver.oldestSupportedTheme; + this.useDayNight = themeResolver.useDayNight; + } + + public Builder setDefaultTheme(@StyleRes int defaultTheme) { + this.defaultTheme = defaultTheme; + return this; + } + + public Builder setOldestSupportedTheme(String oldestSupportedTheme) { + this.oldestSupportedTheme = oldestSupportedTheme; + return this; + } + + public Builder setUseDayNight(boolean useDayNight) { + this.useDayNight = useDayNight; + return this; + } + + public ThemeResolver build() { + return new ThemeResolver(defaultTheme, oldestSupportedTheme, useDayNight); + } + } +} diff --git a/library/main/src/com/android/setupwizardlib/util/WizardManagerHelper.java b/library/main/src/com/android/setupwizardlib/util/WizardManagerHelper.java index 0628192..4d75c78 100644 --- a/library/main/src/com/android/setupwizardlib/util/WizardManagerHelper.java +++ b/library/main/src/com/android/setupwizardlib/util/WizardManagerHelper.java @@ -16,314 +16,390 @@ package com.android.setupwizardlib.util; +import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources.Theme; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.provider.Settings; - +import androidx.annotation.Nullable; import androidx.annotation.StyleRes; import androidx.annotation.VisibleForTesting; - -import com.android.setupwizardlib.R; - import java.util.Arrays; +/** + * Helper to interact with Wizard Manager in setup wizard, which should be used when a screen is + * shown inside the setup flow. This includes things like parsing extras passed by Wizard Manager, + * and invoking Wizard Manager to start the next action. + */ public class WizardManagerHelper { - private static final String ACTION_NEXT = "com.android.wizard.NEXT"; - - // EXTRA_SCRIPT_URI and EXTRA_ACTION_ID are used in setup wizard in versions before M and are - // kept for backwards compatibility. - @VisibleForTesting - static final String EXTRA_SCRIPT_URI = "scriptUri"; - @VisibleForTesting - static final String EXTRA_ACTION_ID = "actionId"; - - @VisibleForTesting - static final String EXTRA_WIZARD_BUNDLE = "wizardBundle"; - private static final String EXTRA_RESULT_CODE = "com.android.setupwizard.ResultCode"; - @VisibleForTesting - static final String EXTRA_IS_FIRST_RUN = "firstRun"; - @VisibleForTesting - static final String EXTRA_IS_DEFERRED_SETUP = "deferredSetup"; - @VisibleForTesting - static final String EXTRA_IS_PRE_DEFERRED_SETUP = "preDeferredSetup"; - - public static final String EXTRA_THEME = "theme"; - public static final String EXTRA_USE_IMMERSIVE_MODE = "useImmersiveMode"; - - public static final String SETTINGS_GLOBAL_DEVICE_PROVISIONED = "device_provisioned"; - public static final String SETTINGS_SECURE_USER_SETUP_COMPLETE = "user_setup_complete"; - - public static final String THEME_HOLO = "holo"; - public static final String THEME_HOLO_LIGHT = "holo_light"; - public static final String THEME_MATERIAL = "material"; - public static final String THEME_MATERIAL_LIGHT = "material_light"; - - /** - * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the dark variant of the - * theme used in setup wizard for Nougat MR1. - */ - public static final String THEME_GLIF = "glif"; - - /** - * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the default theme used in - * setup wizard for Nougat MR1. - */ - public static final String THEME_GLIF_LIGHT = "glif_light"; - - /** - * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the dark variant of the - * theme used in setup wizard for O DR. - */ - public static final String THEME_GLIF_V2 = "glif_v2"; - - /** - * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the default theme used in - * setup wizard for O DR. - */ - public static final String THEME_GLIF_V2_LIGHT = "glif_v2_light"; - - /** - * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the dark variant of the - * theme used in setup wizard for P. - */ - public static final String THEME_GLIF_V3 = "glif_v3"; - - /** - * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the default theme used in - * setup wizard for P. - */ - public static final String THEME_GLIF_V3_LIGHT = "glif_v3_light"; - - /** - * Get an intent that will invoke the next step of setup wizard. - * - * @param originalIntent The original intent that was used to start the step, usually via - * {@link android.app.Activity#getIntent()}. - * @param resultCode The result code of the step. See {@link ResultCodes}. - * @return A new intent that can be used with - * {@link android.app.Activity#startActivityForResult(Intent, int)} to start the next - * step of the setup flow. - */ - public static Intent getNextIntent(Intent originalIntent, int resultCode) { - return getNextIntent(originalIntent, resultCode, null); - } - - /** - * Get an intent that will invoke the next step of setup wizard. - * - * @param originalIntent The original intent that was used to start the step, usually via - * {@link android.app.Activity#getIntent()}. - * @param resultCode The result code of the step. See {@link ResultCodes}. - * @param data An intent containing extra result data. - * @return A new intent that can be used with - * {@link android.app.Activity#startActivityForResult(Intent, int)} to start the next - * step of the setup flow. - */ - public static Intent getNextIntent(Intent originalIntent, int resultCode, Intent data) { - Intent intent = new Intent(ACTION_NEXT); - copyWizardManagerExtras(originalIntent, intent); - intent.putExtra(EXTRA_RESULT_CODE, resultCode); - if (data != null && data.getExtras() != null) { - intent.putExtras(data.getExtras()); - } - intent.putExtra(EXTRA_THEME, originalIntent.getStringExtra(EXTRA_THEME)); - - return intent; - } - - /** - * Copy the internal extras used by setup wizard from one intent to another. For low-level use - * only, such as when using {@link Intent#FLAG_ACTIVITY_FORWARD_RESULT} to relay to another - * intent. - * - * @param srcIntent Intent to get the wizard manager extras from. - * @param dstIntent Intent to copy the wizard manager extras to. - */ - public static void copyWizardManagerExtras(Intent srcIntent, Intent dstIntent) { - dstIntent.putExtra(EXTRA_WIZARD_BUNDLE, srcIntent.getBundleExtra(EXTRA_WIZARD_BUNDLE)); - for (String key : Arrays.asList( - EXTRA_IS_FIRST_RUN, EXTRA_IS_DEFERRED_SETUP, EXTRA_IS_PRE_DEFERRED_SETUP)) { - dstIntent.putExtra(key, srcIntent.getBooleanExtra(key, false)); - } - - for (String key : Arrays.asList(EXTRA_THEME, EXTRA_SCRIPT_URI, EXTRA_ACTION_ID)) { - dstIntent.putExtra(key, srcIntent.getStringExtra(key)); - } - } - - /** - * Check whether an intent is intended to be used within the setup wizard flow. - * - * @param intent The intent to be checked, usually from - * {@link android.app.Activity#getIntent()}. - * @return true if the intent passed in was intended to be used with setup wizard. - */ - public static boolean isSetupWizardIntent(Intent intent) { - return intent.getBooleanExtra(EXTRA_IS_FIRST_RUN, false); + private static final String ACTION_NEXT = "com.android.wizard.NEXT"; + + // EXTRA_SCRIPT_URI and EXTRA_ACTION_ID are used in setup wizard in versions before M and are + // kept for backwards compatibility. + @VisibleForTesting static final String EXTRA_SCRIPT_URI = "scriptUri"; + @VisibleForTesting static final String EXTRA_ACTION_ID = "actionId"; + + @VisibleForTesting static final String EXTRA_WIZARD_BUNDLE = "wizardBundle"; + private static final String EXTRA_RESULT_CODE = "com.android.setupwizard.ResultCode"; + @VisibleForTesting static final String EXTRA_IS_FIRST_RUN = "firstRun"; + @VisibleForTesting static final String EXTRA_IS_DEFERRED_SETUP = "deferredSetup"; + @VisibleForTesting static final String EXTRA_IS_PRE_DEFERRED_SETUP = "preDeferredSetup"; + @VisibleForTesting public static final String EXTRA_IS_SETUP_FLOW = "isSetupFlow"; + + public static final String EXTRA_THEME = "theme"; + public static final String EXTRA_USE_IMMERSIVE_MODE = "useImmersiveMode"; + + public static final String SETTINGS_GLOBAL_DEVICE_PROVISIONED = "device_provisioned"; + public static final String SETTINGS_SECURE_USER_SETUP_COMPLETE = "user_setup_complete"; + + public static final String THEME_HOLO = "holo"; + public static final String THEME_HOLO_LIGHT = "holo_light"; + public static final String THEME_MATERIAL = "material"; + public static final String THEME_MATERIAL_LIGHT = "material_light"; + + /** + * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the dark variant of the theme + * used in setup wizard for Nougat MR1. + */ + public static final String THEME_GLIF = "glif"; + + /** + * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the default theme used in + * setup wizard for Nougat MR1. + */ + public static final String THEME_GLIF_LIGHT = "glif_light"; + + /** + * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the dark variant of the theme + * used in setup wizard for O DR. + */ + public static final String THEME_GLIF_V2 = "glif_v2"; + + /** + * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the default theme used in + * setup wizard for O DR. + */ + public static final String THEME_GLIF_V2_LIGHT = "glif_v2_light"; + + /** + * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the dark variant of the theme + * used in setup wizard for P. + */ + public static final String THEME_GLIF_V3 = "glif_v3"; + + /** + * Passed in a setup wizard intent as {@link #EXTRA_THEME}. This is the default theme used in + * setup wizard for P. + */ + public static final String THEME_GLIF_V3_LIGHT = "glif_v3_light"; + + /** + * Get an intent that will invoke the next step of setup wizard. + * + * @param originalIntent The original intent that was used to start the step, usually via {@link + * android.app.Activity#getIntent()}. + * @param resultCode The result code of the step. See {@link ResultCodes}. + * @return A new intent that can be used with {@link + * android.app.Activity#startActivityForResult(Intent, int)} to start the next step of the + * setup flow. + */ + public static Intent getNextIntent(Intent originalIntent, int resultCode) { + return getNextIntent(originalIntent, resultCode, null); + } + + /** + * Get an intent that will invoke the next step of setup wizard. + * + * @param originalIntent The original intent that was used to start the step, usually via {@link + * android.app.Activity#getIntent()}. + * @param resultCode The result code of the step. See {@link ResultCodes}. + * @param data An intent containing extra result data. + * @return A new intent that can be used with {@link + * android.app.Activity#startActivityForResult(Intent, int)} to start the next step of the + * setup flow. + */ + public static Intent getNextIntent(Intent originalIntent, int resultCode, Intent data) { + Intent intent = new Intent(ACTION_NEXT); + copyWizardManagerExtras(originalIntent, intent); + intent.putExtra(EXTRA_RESULT_CODE, resultCode); + if (data != null && data.getExtras() != null) { + intent.putExtras(data.getExtras()); } - - /** - * Checks whether the current user has completed Setup Wizard. This is true if the current user - * has gone through Setup Wizard. The current user may or may not be the device owner and the - * device owner may have already completed setup wizard. - * - * @param context The context to retrieve the settings. - * @return true if the current user has completed Setup Wizard. - * @see #isDeviceProvisioned(android.content.Context) - */ - public static boolean isUserSetupComplete(Context context) { - if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) { - return Settings.Secure.getInt(context.getContentResolver(), - SETTINGS_SECURE_USER_SETUP_COMPLETE, 0) == 1; - } else { - // For versions below JB MR1, there are no user profiles. Just return the global device - // provisioned state. - return Settings.Secure.getInt(context.getContentResolver(), - SETTINGS_GLOBAL_DEVICE_PROVISIONED, 0) == 1; - } - } - - /** - * Checks whether the device is provisioned. This means that the device has gone through Setup - * Wizard at least once. Note that the user can still be in Setup Wizard even if this is true, - * for a secondary user profile triggered through Settings > Add account. - * - * @param context The context to retrieve the settings. - * @return true if the device is provisioned. - * @see #isUserSetupComplete(android.content.Context) - */ - public static boolean isDeviceProvisioned(Context context) { - if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) { - return Settings.Global.getInt(context.getContentResolver(), - SETTINGS_GLOBAL_DEVICE_PROVISIONED, 0) == 1; - } else { - return Settings.Secure.getInt(context.getContentResolver(), - SETTINGS_GLOBAL_DEVICE_PROVISIONED, 0) == 1; - } - } - - /** - * Checks whether an intent is running in the deferred setup wizard flow. - * - * @param originalIntent The original intent that was used to start the step, usually via - * {@link android.app.Activity#getIntent()}. - * @return true if the intent passed in was running in deferred setup wizard. - */ - public static boolean isDeferredSetupWizard(Intent originalIntent) { - return originalIntent != null - && originalIntent.getBooleanExtra(EXTRA_IS_DEFERRED_SETUP, false); + intent.putExtra(EXTRA_THEME, originalIntent.getStringExtra(EXTRA_THEME)); + + return intent; + } + + /** + * Copy the internal extras used by setup wizard from one intent to another. For low-level use + * only, such as when using {@link Intent#FLAG_ACTIVITY_FORWARD_RESULT} to relay to another + * intent. + * + * @param srcIntent Intent to get the wizard manager extras from. + * @param dstIntent Intent to copy the wizard manager extras to. + */ + public static void copyWizardManagerExtras(Intent srcIntent, Intent dstIntent) { + dstIntent.putExtra(EXTRA_WIZARD_BUNDLE, srcIntent.getBundleExtra(EXTRA_WIZARD_BUNDLE)); + for (String key : + Arrays.asList( + EXTRA_IS_FIRST_RUN, + EXTRA_IS_DEFERRED_SETUP, + EXTRA_IS_PRE_DEFERRED_SETUP, + EXTRA_IS_SETUP_FLOW)) { + dstIntent.putExtra(key, srcIntent.getBooleanExtra(key, false)); } - /** - * Checks whether an intent is running in "pre-deferred" setup wizard flow. - * - * @param originalIntent The original intent that was used to start the step, usually via - * {@link android.app.Activity#getIntent()}. - * @return true if the intent passed in was running in "pre-deferred" setup wizard. - */ - public static boolean isPreDeferredSetupWizard(Intent originalIntent) { - return originalIntent != null - && originalIntent.getBooleanExtra(EXTRA_IS_PRE_DEFERRED_SETUP, false); + for (String key : Arrays.asList(EXTRA_THEME, EXTRA_SCRIPT_URI, EXTRA_ACTION_ID)) { + dstIntent.putExtra(key, srcIntent.getStringExtra(key)); } - - /** - * Checks the intent whether the extra indicates that the light theme should be used or not. If - * the theme is not specified in the intent, or the theme specified is unknown, the value def - * will be returned. - * - * @param intent The intent used to start the activity, which the theme extra will be read from. - * @param def The default value if the theme is not specified. - * @return True if the activity started by the given intent should use light theme. - */ - public static boolean isLightTheme(Intent intent, boolean def) { - final String theme = intent.getStringExtra(EXTRA_THEME); - return isLightTheme(theme, def); + } + + /** + * Check whether an intent is intended to be used within the setup wizard flow. + * + * @param intent The intent to be checked, usually from {@link android.app.Activity#getIntent()}. + * @return true if the intent passed in was intended to be used with setup wizard. + */ + public static boolean isSetupWizardIntent(Intent intent) { + return intent.getBooleanExtra(EXTRA_IS_FIRST_RUN, false); + } + + /** + * Checks whether the current user has completed Setup Wizard. This is true if the current user + * has gone through Setup Wizard. The current user may or may not be the device owner and the + * device owner may have already completed setup wizard. + * + * @param context The context to retrieve the settings. + * @return true if the current user has completed Setup Wizard. + * @see #isDeviceProvisioned(android.content.Context) + */ + public static boolean isUserSetupComplete(Context context) { + if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) { + return Settings.Secure.getInt( + context.getContentResolver(), SETTINGS_SECURE_USER_SETUP_COMPLETE, 0) + == 1; + } else { + // For versions below JB MR1, there are no user profiles. Just return the global device + // provisioned state. + return Settings.Secure.getInt( + context.getContentResolver(), SETTINGS_GLOBAL_DEVICE_PROVISIONED, 0) + == 1; } - - /** - * Checks whether {@code theme} represents a light or dark theme. If the theme specified is - * unknown, the value def will be returned. - * - * @param theme The theme as specified from an intent sent from setup wizard. - * @param def The default value if the theme is not known. - * @return True if {@code theme} represents a light theme. - */ - public static boolean isLightTheme(String theme, boolean def) { - if (THEME_HOLO_LIGHT.equals(theme) || THEME_MATERIAL_LIGHT.equals(theme) - || THEME_GLIF_LIGHT.equals(theme) || THEME_GLIF_V2_LIGHT.equals(theme) - || THEME_GLIF_V3_LIGHT.equals(theme)) { - return true; - } else if (THEME_HOLO.equals(theme) || THEME_MATERIAL.equals(theme) - || THEME_GLIF.equals(theme) || THEME_GLIF_V2.equals(theme) - || THEME_GLIF_V3.equals(theme)) { - return false; - } else { - return def; - } + } + + /** + * Checks whether the device is provisioned. This means that the device has gone through Setup + * Wizard at least once. Note that the user can still be in Setup Wizard even if this is true, for + * a secondary user profile triggered through Settings > Add account. + * + * @param context The context to retrieve the settings. + * @return true if the device is provisioned. + * @see #isUserSetupComplete(android.content.Context) + */ + public static boolean isDeviceProvisioned(Context context) { + if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) { + return Settings.Global.getInt( + context.getContentResolver(), SETTINGS_GLOBAL_DEVICE_PROVISIONED, 0) + == 1; + } else { + return Settings.Secure.getInt( + context.getContentResolver(), SETTINGS_GLOBAL_DEVICE_PROVISIONED, 0) + == 1; } - - /** - * Gets the theme style resource defined by this library for the theme specified in the given - * intent. For example, for THEME_GLIF_LIGHT, the theme @style/SuwThemeGlif.Light is returned. - * - * @param intent The intent passed by setup wizard, or one with the theme propagated along using - * {@link #copyWizardManagerExtras(Intent, Intent)}. - * @return The style corresponding to the theme in the given intent, or {@code defaultTheme} if - * the given theme is not recognized. - * - * @see #getThemeRes(String, int) - */ - public static @StyleRes int getThemeRes(Intent intent, @StyleRes int defaultTheme) { - final String theme = intent.getStringExtra(EXTRA_THEME); - return getThemeRes(theme, defaultTheme); - } - - /** - * Gets the theme style resource defined by this library for the given theme name. For example, - * for THEME_GLIF_LIGHT, the theme @style/SuwThemeGlif.Light is returned. - * - * <p>If you require extra theme attributes but want to ensure forward compatibility with new - * themes added here, consider overriding {@link android.app.Activity#onApplyThemeResource} in - * your activity and call {@link Theme#applyStyle(int, boolean)} using your theme overlay. - * - * <pre>{@code - * protected void onApplyThemeResource(Theme theme, int resid, boolean first) { - * super.onApplyThemeResource(theme, resid, first); - * theme.applyStyle(R.style.MyThemeOverlay, true); - * } - * }</pre> - * - * @param theme The string representation of the theme. - * @return The style corresponding to the given {@code theme}, or {@code defaultTheme} if the - * given theme is not recognized. - */ - public static @StyleRes int getThemeRes(String theme, @StyleRes int defaultTheme) { - if (theme != null) { - switch (theme) { - case THEME_GLIF_V3_LIGHT: - return R.style.SuwThemeGlifV3_Light; - case THEME_GLIF_V3: - return R.style.SuwThemeGlifV3; - case THEME_GLIF_V2_LIGHT: - return R.style.SuwThemeGlifV2_Light; - case THEME_GLIF_V2: - return R.style.SuwThemeGlifV2; - case THEME_GLIF_LIGHT: - return R.style.SuwThemeGlif_Light; - case THEME_GLIF: - return R.style.SuwThemeGlif; - case THEME_MATERIAL_LIGHT: - return R.style.SuwThemeMaterial_Light; - case THEME_MATERIAL: - return R.style.SuwThemeMaterial; - default: - // fall through - } - } - return defaultTheme; + } + + /** + * Checks whether an intent is running in the deferred setup wizard flow. + * + * @param originalIntent The original intent that was used to start the step, usually via {@link + * android.app.Activity#getIntent()}. + * @return true if the intent passed in was running in deferred setup wizard. + */ + public static boolean isDeferredSetupWizard(Intent originalIntent) { + return originalIntent != null && originalIntent.getBooleanExtra(EXTRA_IS_DEFERRED_SETUP, false); + } + + /** + * Checks whether an intent is running in "pre-deferred" setup wizard flow. + * + * @param originalIntent The original intent that was used to start the step, usually via {@link + * android.app.Activity#getIntent()}. + * @return true if the intent passed in was running in "pre-deferred" setup wizard. + */ + public static boolean isPreDeferredSetupWizard(Intent originalIntent) { + return originalIntent != null + && originalIntent.getBooleanExtra(EXTRA_IS_PRE_DEFERRED_SETUP, false); + } + + /** + * Checks the intent whether the extra indicates that the light theme should be used or not. If + * the theme is not specified in the intent, or the theme specified is unknown, the value def will + * be returned. Note that day-night themes are not taken into account by this method. + * + * @param intent The intent used to start the activity, which the theme extra will be read from. + * @param def The default value if the theme is not specified. + * @return True if the activity started by the given intent should use light theme. + */ + public static boolean isLightTheme(Intent intent, boolean def) { + final String theme = intent.getStringExtra(EXTRA_THEME); + return isLightTheme(theme, def); + } + + /** + * Checks whether {@code theme} represents a light or dark theme. If the theme specified is + * unknown, the value def will be returned. Note that day-night themes are not taken into account + * by this method. + * + * @param theme The theme as specified from an intent sent from setup wizard. + * @param def The default value if the theme is not known. + * @return True if {@code theme} represents a light theme. + */ + public static boolean isLightTheme(String theme, boolean def) { + if (THEME_HOLO_LIGHT.equals(theme) + || THEME_MATERIAL_LIGHT.equals(theme) + || THEME_GLIF_LIGHT.equals(theme) + || THEME_GLIF_V2_LIGHT.equals(theme) + || THEME_GLIF_V3_LIGHT.equals(theme)) { + return true; + } else if (THEME_HOLO.equals(theme) + || THEME_MATERIAL.equals(theme) + || THEME_GLIF.equals(theme) + || THEME_GLIF_V2.equals(theme) + || THEME_GLIF_V3.equals(theme)) { + return false; + } else { + return def; } + } + + /** + * Gets the theme style resource defined by this library for the theme specified in the given + * intent. For example, for THEME_GLIF_LIGHT, the theme @style/SuwThemeGlif.Light is returned. + * + * @param intent The intent passed by setup wizard, or one with the theme propagated along using + * {@link #copyWizardManagerExtras(Intent, Intent)}. + * @return The style corresponding to the theme in the given intent, or {@code defaultTheme} if + * the given theme is not recognized. + * @see #getThemeRes(String, int) + * @deprecated it is recommended to use {@link ThemeResolver} which allows setting the default + * theme in one place and applying it to multiple screens. + */ + @Deprecated + public static @StyleRes int getThemeRes(Intent intent, @StyleRes int defaultTheme) { + return new ThemeResolver.Builder(ThemeResolver.getDefault()) + .setDefaultTheme(defaultTheme) + .setUseDayNight(false) + .build() + .resolve(intent); + } + + /** + * Gets the theme style resource defined by this library for the theme specified in the given + * intent. For example, for THEME_GLIF_LIGHT, the theme @style/SuwThemeGlif.Light is returned. + * + * @param intent The intent passed by setup wizard, or one with the theme propagated along using + * {@link #copyWizardManagerExtras(Intent, Intent)}. + * @return The style corresponding to the theme in the given intent, or {@code defaultTheme} if + * the given theme is not recognized. Return the {@code defaultTheme} if the specified theme + * is older than the oldest supported one. + * @see #getThemeRes(String, int) + * @deprecated it is recommended to use {@link ThemeResolver} which allows setting the default + * theme and oldest supported theme in one place and applying it to multiple screens. + */ + @Deprecated + public static @StyleRes int getThemeRes( + Intent intent, @StyleRes int defaultTheme, @Nullable String oldestSupportedTheme) { + return new ThemeResolver.Builder(ThemeResolver.getDefault()) + .setDefaultTheme(defaultTheme) + .setUseDayNight(false) + .setOldestSupportedTheme(oldestSupportedTheme) + .build() + .resolve(intent); + } + + /** + * Gets the theme style resource defined by this library for the given theme name. For example, + * for THEME_GLIF_LIGHT, the theme @style/SuwThemeGlif.Light is returned. + * + * <p>If you require extra theme attributes but want to ensure forward compatibility with new + * themes added here, consider overriding {@link android.app.Activity#onApplyThemeResource} in + * your activity and call {@link Theme#applyStyle(int, boolean)} using your theme overlay. + * + * <pre>{@code + * protected void onApplyThemeResource(Theme theme, int resid, boolean first) { + * super.onApplyThemeResource(theme, resid, first); + * theme.applyStyle(R.style.MyThemeOverlay, true); + * } + * }</pre> + * + * @param theme The string representation of the theme. + * @return The style corresponding to the given {@code theme}, or {@code defaultTheme} if the + * given theme is not recognized. + * @deprecated it is recommended to use {@link ThemeResolver} which allows setting the default + * theme in one place and applying it to multiple screens. + */ + @Deprecated + public static @StyleRes int getThemeRes( + String theme, @StyleRes int defaultTheme, @Nullable String oldestSupportedTheme) { + return new ThemeResolver.Builder(ThemeResolver.getDefault()) + .setDefaultTheme(defaultTheme) + .setUseDayNight(false) + .setOldestSupportedTheme(oldestSupportedTheme) + .build() + .resolve(theme); + } + + /** + * Gets the theme style resource defined by this library for the given theme name. For example, + * for THEME_GLIF_LIGHT, the theme @style/SuwThemeGlif.Light is returned. + * + * <p>If you require extra theme attributes but want to ensure forward compatibility with new + * themes added here, consider overriding {@link android.app.Activity#onApplyThemeResource} in + * your activity and call {@link Theme#applyStyle(int, boolean)} using your theme overlay. + * + * <pre>{@code + * protected void onApplyThemeResource(Theme theme, int resid, boolean first) { + * super.onApplyThemeResource(theme, resid, first); + * theme.applyStyle(R.style.MyThemeOverlay, true); + * } + * }</pre> + * + * @param theme The string representation of the theme. + * @return The style corresponding to the given {@code theme}, or {@code defaultTheme} if the + * given theme is not recognized. + * @deprecated it is recommended to use {@link ThemeResolver} which allows setting the default + * theme in one place and applying it to multiple screens. + */ + @Deprecated + public static @StyleRes int getThemeRes(@Nullable String theme, @StyleRes int defaultTheme) { + return new ThemeResolver.Builder(ThemeResolver.getDefault()) + .setDefaultTheme(defaultTheme) + .setUseDayNight(false) + .build() + .resolve(theme); + } + + /** + * Reads the theme from the intent, and applies the theme to the activity as resolved by {@link + * ThemeResolver#getDefault()}. + * + * <p>If you require extra theme attributes, consider overriding {@link + * android.app.Activity#onApplyThemeResource} in your activity and call {@link + * Theme#applyStyle(int, boolean)} using your theme overlay. + * + * <pre>{@code + * protected void onApplyThemeResource(Theme theme, int resid, boolean first) { + * super.onApplyThemeResource(theme, resid, first); + * theme.applyStyle(R.style.MyThemeOverlay, true); + * } + * }</pre> + * + * @param activity the activity to get the intent from and apply the resulting theme to. + */ + public static void applyTheme(Activity activity) { + ThemeResolver.getDefault().applyTheme(activity); + } } diff --git a/library/main/src/com/android/setupwizardlib/view/BottomScrollView.java b/library/main/src/com/android/setupwizardlib/view/BottomScrollView.java index eeb40a9..962538f 100644 --- a/library/main/src/com/android/setupwizardlib/view/BottomScrollView.java +++ b/library/main/src/com/android/setupwizardlib/view/BottomScrollView.java @@ -17,12 +17,11 @@ package com.android.setupwizardlib.view; import android.content.Context; +import androidx.annotation.VisibleForTesting; import android.util.AttributeSet; import android.view.View; import android.widget.ScrollView; -import androidx.annotation.VisibleForTesting; - /** * An extension of ScrollView that will invoke a listener callback when the ScrollView needs * scrolling, and when the ScrollView is being scrolled to the bottom. This is often used in Setup @@ -30,75 +29,81 @@ import androidx.annotation.VisibleForTesting; */ public class BottomScrollView extends ScrollView { - public interface BottomScrollListener { - void onScrolledToBottom(); - void onRequiresScroll(); - } + public interface BottomScrollListener { + void onScrolledToBottom(); + + void onRequiresScroll(); + } - private BottomScrollListener mListener; - private int mScrollThreshold; - private boolean mRequiringScroll = false; + private BottomScrollListener listener; + private int scrollThreshold; + private boolean requiringScroll = false; - private final Runnable mCheckScrollRunnable = new Runnable() { + private final Runnable checkScrollRunnable = + new Runnable() { @Override public void run() { - checkScroll(); + checkScroll(); } - }; - - public BottomScrollView(Context context) { - super(context); + }; + + public BottomScrollView(Context context) { + super(context); + } + + public BottomScrollView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public BottomScrollView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + public void setBottomScrollListener(BottomScrollListener l) { + listener = l; + } + + @VisibleForTesting + public BottomScrollListener getBottomScrollListener() { + return listener; + } + + @VisibleForTesting + public int getScrollThreshold() { + return scrollThreshold; + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + super.onLayout(changed, l, t, r, b); + final View child = getChildAt(0); + if (child != null) { + scrollThreshold = Math.max(0, child.getMeasuredHeight() - b + t - getPaddingBottom()); } - - public BottomScrollView(Context context, AttributeSet attrs) { - super(context, attrs); + if (b - t > 0) { + // Post check scroll in the next run loop, so that the callback methods will be invoked + // after the layout pass. This way a new layout pass will be scheduled if view + // properties are changed in the callbacks. + post(checkScrollRunnable); } + } - public BottomScrollView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); + @Override + protected void onScrollChanged(int l, int t, int oldl, int oldt) { + super.onScrollChanged(l, t, oldl, oldt); + if (oldt != t) { + checkScroll(); } - - public void setBottomScrollListener(BottomScrollListener l) { - mListener = l; + } + + private void checkScroll() { + if (listener != null) { + if (getScrollY() >= scrollThreshold) { + listener.onScrolledToBottom(); + } else if (!requiringScroll) { + requiringScroll = true; + listener.onRequiresScroll(); + } } - - @VisibleForTesting - public int getScrollThreshold() { - return mScrollThreshold; - } - - @Override - protected void onLayout(boolean changed, int l, int t, int r, int b) { - super.onLayout(changed, l, t, r, b); - final View child = getChildAt(0); - if (child != null) { - mScrollThreshold = Math.max(0, child.getMeasuredHeight() - b + t - getPaddingBottom()); - } - if (b - t > 0) { - // Post check scroll in the next run loop, so that the callback methods will be invoked - // after the layout pass. This way a new layout pass will be scheduled if view - // properties are changed in the callbacks. - post(mCheckScrollRunnable); - } - } - - @Override - protected void onScrollChanged(int l, int t, int oldl, int oldt) { - super.onScrollChanged(l, t, oldl, oldt); - if (oldt != t) { - checkScroll(); - } - } - - private void checkScroll() { - if (mListener != null) { - if (getScrollY() >= mScrollThreshold) { - mListener.onScrolledToBottom(); - } else if (!mRequiringScroll) { - mRequiringScroll = true; - mListener.onRequiresScroll(); - } - } - } - + } } diff --git a/library/main/src/com/android/setupwizardlib/view/ButtonBarLayout.java b/library/main/src/com/android/setupwizardlib/view/ButtonBarLayout.java index f7f5f99..4be4f56 100644 --- a/library/main/src/com/android/setupwizardlib/view/ButtonBarLayout.java +++ b/library/main/src/com/android/setupwizardlib/view/ButtonBarLayout.java @@ -20,105 +20,99 @@ import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; - import com.android.setupwizardlib.R; /** * An extension of LinearLayout that automatically switches to vertical orientation when it can't * fit its child views horizontally. * - * Modified from {@code com.android.internal.widget.ButtonBarLayout} + * <p>Modified from {@code com.android.internal.widget.ButtonBarLayout} */ public class ButtonBarLayout extends LinearLayout { - private boolean mStacked = false; - private int mOriginalPaddingLeft; - private int mOriginalPaddingRight; + private boolean stacked = false; + private int originalPaddingLeft; + private int originalPaddingRight; - public ButtonBarLayout(Context context) { - super(context); - } + public ButtonBarLayout(Context context) { + super(context); + } - public ButtonBarLayout(Context context, AttributeSet attrs) { - super(context, attrs); - } + public ButtonBarLayout(Context context, AttributeSet attrs) { + super(context, attrs); + } - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - final int widthSize = MeasureSpec.getSize(widthMeasureSpec); + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + final int widthSize = MeasureSpec.getSize(widthMeasureSpec); - setStacked(false); + setStacked(false); - boolean needsRemeasure = false; + boolean needsRemeasure = false; - int initialWidthMeasureSpec = widthMeasureSpec; - if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY) { - // Measure with WRAP_CONTENT, so that we can compare the measured size with the - // available size to see if we need to stack. - initialWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); + int initialWidthMeasureSpec = widthMeasureSpec; + if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY) { + // Measure with WRAP_CONTENT, so that we can compare the measured size with the + // available size to see if we need to stack. + initialWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - // We'll need to remeasure again to fill excess space. - needsRemeasure = true; - } + // We'll need to remeasure again to fill excess space. + needsRemeasure = true; + } - super.onMeasure(initialWidthMeasureSpec, heightMeasureSpec); + super.onMeasure(initialWidthMeasureSpec, heightMeasureSpec); - if (getMeasuredWidth() > widthSize) { - setStacked(true); + if (getMeasuredWidth() > widthSize) { + setStacked(true); - // Measure again in the new orientation. - needsRemeasure = true; - } + // Measure again in the new orientation. + needsRemeasure = true; + } - if (needsRemeasure) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - } + if (needsRemeasure) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); } + } - private void setStacked(boolean stacked) { - if (mStacked == stacked) { - return; - } - mStacked = stacked; - int childCount = getChildCount(); - for (int i = 0; i < childCount; i++) { - View child = getChildAt(i); - LayoutParams childParams = (LayoutParams) child.getLayoutParams(); - if (stacked) { - child.setTag(R.id.suw_original_weight, childParams.weight); - childParams.weight = 0; - } else { - Float weight = (Float) child.getTag(R.id.suw_original_weight); - if (weight != null) { - childParams.weight = weight; - } - } - child.setLayoutParams(childParams); + private void setStacked(boolean stacked) { + if (this.stacked == stacked) { + return; + } + this.stacked = stacked; + int childCount = getChildCount(); + for (int i = 0; i < childCount; i++) { + View child = getChildAt(i); + LayoutParams childParams = (LayoutParams) child.getLayoutParams(); + if (stacked) { + child.setTag(R.id.suw_original_weight, childParams.weight); + childParams.weight = 0; + } else { + Float weight = (Float) child.getTag(R.id.suw_original_weight); + if (weight != null) { + childParams.weight = weight; } + } + child.setLayoutParams(childParams); + } - setOrientation(stacked ? LinearLayout.VERTICAL : LinearLayout.HORIZONTAL); + setOrientation(stacked ? LinearLayout.VERTICAL : LinearLayout.HORIZONTAL); - // Reverse the child order, so that the primary button is towards the top when vertical - for (int i = childCount - 1; i >= 0; i--) { - bringChildToFront(getChildAt(i)); - } + // Reverse the child order, so that the primary button is towards the top when vertical + for (int i = childCount - 1; i >= 0; i--) { + bringChildToFront(getChildAt(i)); + } - if (stacked) { - // HACK: In the default button bar style, the left and right paddings are not - // balanced to compensate for different alignment for borderless (left) button and - // the raised (right) button. When it's stacked, we want the buttons to be centered, - // so we balance out the paddings here. - mOriginalPaddingLeft = getPaddingLeft(); - mOriginalPaddingRight = getPaddingRight(); - int paddingHorizontal = Math.max(mOriginalPaddingLeft, mOriginalPaddingRight); - setPadding( - paddingHorizontal, getPaddingTop(), paddingHorizontal, getPaddingBottom()); - } else { - setPadding( - mOriginalPaddingLeft, - getPaddingTop(), - mOriginalPaddingRight, - getPaddingBottom()); - } + if (stacked) { + // HACK: In the default button bar style, the left and right paddings are not + // balanced to compensate for different alignment for borderless (left) button and + // the raised (right) button. When it's stacked, we want the buttons to be centered, + // so we balance out the paddings here. + originalPaddingLeft = getPaddingLeft(); + originalPaddingRight = getPaddingRight(); + int paddingHorizontal = Math.max(originalPaddingLeft, originalPaddingRight); + setPadding(paddingHorizontal, getPaddingTop(), paddingHorizontal, getPaddingBottom()); + } else { + setPadding(originalPaddingLeft, getPaddingTop(), originalPaddingRight, getPaddingBottom()); } + } } diff --git a/library/main/src/com/android/setupwizardlib/view/CheckableLinearLayout.java b/library/main/src/com/android/setupwizardlib/view/CheckableLinearLayout.java index 9605f99..fd2319c 100644 --- a/library/main/src/com/android/setupwizardlib/view/CheckableLinearLayout.java +++ b/library/main/src/com/android/setupwizardlib/view/CheckableLinearLayout.java @@ -19,74 +19,67 @@ package com.android.setupwizardlib.view; import android.annotation.TargetApi; import android.content.Context; import android.os.Build.VERSION_CODES; +import androidx.annotation.Nullable; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.LinearLayout; -import androidx.annotation.Nullable; - /** - * A LinearLayout which is checkable. This will set the checked state when - * {@link #onCreateDrawableState(int)} is called, and can be used with - * {@code android:duplicateParentState} to propagate the drawable state to child views. + * A LinearLayout which is checkable. This will set the checked state when {@link + * #onCreateDrawableState(int)} is called, and can be used with {@code android:duplicateParentState} + * to propagate the drawable state to child views. */ public class CheckableLinearLayout extends LinearLayout implements Checkable { - private boolean mChecked = false; + private boolean checked = false; - public CheckableLinearLayout(Context context) { - super(context); - } + public CheckableLinearLayout(Context context) { + super(context); + } - public CheckableLinearLayout(Context context, @Nullable AttributeSet attrs) { - super(context, attrs); - } + public CheckableLinearLayout(Context context, @Nullable AttributeSet attrs) { + super(context, attrs); + } - @TargetApi(VERSION_CODES.HONEYCOMB) - public CheckableLinearLayout( - Context context, - @Nullable AttributeSet attrs, - int defStyleAttr) { - super(context, attrs, defStyleAttr); - } + @TargetApi(VERSION_CODES.HONEYCOMB) + public CheckableLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } - @TargetApi(VERSION_CODES.LOLLIPOP) - public CheckableLinearLayout( - Context context, - AttributeSet attrs, - int defStyleAttr, - int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); - } + @TargetApi(VERSION_CODES.LOLLIPOP) + public CheckableLinearLayout( + Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + } - { - setFocusable(true); - } + { + setFocusable(true); + } - @Override - protected int[] onCreateDrawableState(int extraSpace) { - if (mChecked) { - final int[] superStates = super.onCreateDrawableState(extraSpace + 1); - final int[] checked = new int[] { android.R.attr.state_checked }; - return mergeDrawableStates(superStates, checked); - } else { - return super.onCreateDrawableState(extraSpace); - } + @Override + protected int[] onCreateDrawableState(int extraSpace) { + if (this.checked) { + final int[] superStates = super.onCreateDrawableState(extraSpace + 1); + final int[] checked = new int[] {android.R.attr.state_checked}; + return mergeDrawableStates(superStates, checked); + } else { + return super.onCreateDrawableState(extraSpace); } + } - @Override - public void setChecked(boolean checked) { - mChecked = checked; - refreshDrawableState(); - } + @Override + public void setChecked(boolean checked) { + this.checked = checked; + refreshDrawableState(); + } - @Override - public boolean isChecked() { - return mChecked; - } + @Override + public boolean isChecked() { + return checked; + } - @Override - public void toggle() { - setChecked(!isChecked()); - } + @Override + public void toggle() { + setChecked(!isChecked()); + } } diff --git a/library/main/src/com/android/setupwizardlib/view/FillContentLayout.java b/library/main/src/com/android/setupwizardlib/view/FillContentLayout.java index 2c28090..b72d4d2 100644 --- a/library/main/src/com/android/setupwizardlib/view/FillContentLayout.java +++ b/library/main/src/com/android/setupwizardlib/view/FillContentLayout.java @@ -21,13 +21,12 @@ import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; - import com.android.setupwizardlib.R; /** - * A layout that will measure its children size based on the space it is given, by using its - * {@code android:minWidth}, {@code android:minHeight}, {@code android:maxWidth}, and - * {@code android:maxHeight} values. + * A layout that will measure its children size based on the space it is given, by using its {@code + * android:minWidth}, {@code android:minHeight}, {@code android:maxWidth}, and {@code + * android:maxHeight} values. * * <p>Typically this is used to show an illustration image or video on the screen. For optimal UX, * those assets typically want to occupy the remaining space available on screen within a certain @@ -42,84 +41,82 @@ import com.android.setupwizardlib.R; */ public class FillContentLayout extends FrameLayout { - private int mMaxWidth; - private int mMaxHeight; - - public FillContentLayout(Context context) { - this(context, null); - } - - public FillContentLayout(Context context, AttributeSet attrs) { - this(context, attrs, R.attr.suwFillContentLayoutStyle); - } - - public FillContentLayout(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(context, attrs, defStyleAttr); - } + private int maxWidth; + private int maxHeight; - private void init(Context context, AttributeSet attrs, int defStyleAttr) { - TypedArray a = context.obtainStyledAttributes( - attrs, - R.styleable.SuwFillContentLayout, - defStyleAttr, - 0); + public FillContentLayout(Context context) { + this(context, null); + } - mMaxHeight = a.getDimensionPixelSize( - R.styleable.SuwFillContentLayout_android_maxHeight, -1); - mMaxWidth = a.getDimensionPixelSize(R.styleable.SuwFillContentLayout_android_maxWidth, -1); + public FillContentLayout(Context context, AttributeSet attrs) { + this(context, attrs, R.attr.suwFillContentLayoutStyle); + } - a.recycle(); - } + public FillContentLayout(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(context, attrs, defStyleAttr); + } - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - // Measure this view with the minWidth and minHeight, without asking the children. - // (Children size is the drawable's intrinsic size, and we don't want that to influence - // the size of the illustration). - setMeasuredDimension( - getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), - getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); - - int childCount = getChildCount(); - for (int i = 0; i < childCount; i++) { - measureIllustrationChild(getChildAt(i), getMeasuredWidth(), getMeasuredHeight()); - } - } + private void init(Context context, AttributeSet attrs, int defStyleAttr) { + TypedArray a = + context.obtainStyledAttributes(attrs, R.styleable.SuwFillContentLayout, defStyleAttr, 0); - private void measureIllustrationChild(View child, int parentWidth, int parentHeight) { - // Modified from ViewGroup#measureChildWithMargins - final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); + maxHeight = a.getDimensionPixelSize(R.styleable.SuwFillContentLayout_android_maxHeight, -1); + maxWidth = a.getDimensionPixelSize(R.styleable.SuwFillContentLayout_android_maxWidth, -1); - // Create measure specs that are no bigger than min(parentSize, maxSize) + a.recycle(); + } - int childWidthMeasureSpec = getMaxSizeMeasureSpec( - Math.min(mMaxWidth, parentWidth), - getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, - lp.width); - int childHeightMeasureSpec = getMaxSizeMeasureSpec( - Math.min(mMaxHeight, parentHeight), - getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin, - lp.height); + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + // Measure this view with the minWidth and minHeight, without asking the children. + // (Children size is the drawable's intrinsic size, and we don't want that to influence + // the size of the illustration). + setMeasuredDimension( + getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), + getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); - child.measure(childWidthMeasureSpec, childHeightMeasureSpec); + int childCount = getChildCount(); + for (int i = 0; i < childCount; i++) { + measureIllustrationChild(getChildAt(i), getMeasuredWidth(), getMeasuredHeight()); } - - private static int getMaxSizeMeasureSpec(int maxSize, int padding, int childDimension) { - // Modified from ViewGroup#getChildMeasureSpec - int size = Math.max(0, maxSize - padding); - - if (childDimension >= 0) { - // Child wants a specific size... so be it - return MeasureSpec.makeMeasureSpec(childDimension, MeasureSpec.EXACTLY); - } else if (childDimension == LayoutParams.MATCH_PARENT) { - // Child wants to be our size. So be it. - return MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY); - } else if (childDimension == LayoutParams.WRAP_CONTENT) { - // Child wants to determine its own size. It can't be - // bigger than us. - return MeasureSpec.makeMeasureSpec(size, MeasureSpec.AT_MOST); - } - return 0; + } + + private void measureIllustrationChild(View child, int parentWidth, int parentHeight) { + // Modified from ViewGroup#measureChildWithMargins + final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); + + // Create measure specs that are no bigger than min(parentSize, maxSize) + + int childWidthMeasureSpec = + getMaxSizeMeasureSpec( + Math.min(maxWidth, parentWidth), + getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, + lp.width); + int childHeightMeasureSpec = + getMaxSizeMeasureSpec( + Math.min(maxHeight, parentHeight), + getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin, + lp.height); + + child.measure(childWidthMeasureSpec, childHeightMeasureSpec); + } + + private static int getMaxSizeMeasureSpec(int maxSize, int padding, int childDimension) { + // Modified from ViewGroup#getChildMeasureSpec + int size = Math.max(0, maxSize - padding); + + if (childDimension >= 0) { + // Child wants a specific size... so be it + return MeasureSpec.makeMeasureSpec(childDimension, MeasureSpec.EXACTLY); + } else if (childDimension == LayoutParams.MATCH_PARENT) { + // Child wants to be our size. So be it. + return MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY); + } else if (childDimension == LayoutParams.WRAP_CONTENT) { + // Child wants to determine its own size. It can't be + // bigger than us. + return MeasureSpec.makeMeasureSpec(size, MeasureSpec.AT_MOST); } + return 0; + } } diff --git a/library/main/src/com/android/setupwizardlib/view/Illustration.java b/library/main/src/com/android/setupwizardlib/view/Illustration.java index c6968f8..e9cd4b5 100644 --- a/library/main/src/com/android/setupwizardlib/view/Illustration.java +++ b/library/main/src/com/android/setupwizardlib/view/Illustration.java @@ -30,7 +30,6 @@ import android.util.LayoutDirection; import android.view.Gravity; import android.view.ViewOutlineProvider; import android.widget.FrameLayout; - import com.android.setupwizardlib.R; /** @@ -39,184 +38,190 @@ import com.android.setupwizardlib.R; * drawable to fit the width of the view and fills the rest with the background. * * <p>If an aspect ratio is set, then the aspect ratio of the source drawable is maintained. - * Otherwise the the aspect ratio will be ignored, only increasing the width of the illustration. + * Otherwise the aspect ratio will be ignored, only increasing the width of the illustration. */ public class Illustration extends FrameLayout { - // Size of the baseline grid in pixels - private float mBaselineGridSize; - private Drawable mBackground; - private Drawable mIllustration; - private final Rect mViewBounds = new Rect(); - private final Rect mIllustrationBounds = new Rect(); - private float mScale = 1.0f; - private float mAspectRatio = 0.0f; - - public Illustration(Context context) { - super(context); - init(null, 0); - } - - public Illustration(Context context, AttributeSet attrs) { - super(context, attrs); - init(attrs, 0); + // Size of the baseline grid in pixels + private float baselineGridSize; + private Drawable background; + private Drawable illustration; + private final Rect viewBounds = new Rect(); + private final Rect illustrationBounds = new Rect(); + private float scale = 1.0f; + private float aspectRatio = 0.0f; + + public Illustration(Context context) { + super(context); + init(null, 0); + } + + public Illustration(Context context, AttributeSet attrs) { + super(context, attrs); + init(attrs, 0); + } + + @TargetApi(VERSION_CODES.HONEYCOMB) + public Illustration(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(attrs, defStyleAttr); + } + + // All the constructors delegate to this init method. The 3-argument constructor is not + // available in FrameLayout before v11, so call super with the exact same arguments. + private void init(AttributeSet attrs, int defStyleAttr) { + if (attrs != null) { + TypedArray a = + getContext().obtainStyledAttributes(attrs, R.styleable.SuwIllustration, defStyleAttr, 0); + aspectRatio = a.getFloat(R.styleable.SuwIllustration_suwAspectRatio, 0.0f); + a.recycle(); } - - @TargetApi(VERSION_CODES.HONEYCOMB) - public Illustration(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(attrs, defStyleAttr); + // Number of pixels of the 8dp baseline grid as defined in material design specs + baselineGridSize = getResources().getDisplayMetrics().density * 8; + setWillNotDraw(false); + } + + /** + * The background will be drawn to fill up the rest of the view. It will also be scaled by the + * same amount as the foreground so their textures look the same. + */ + // Override the deprecated setBackgroundDrawable method to support API < 16. View.setBackground + // forwards to setBackgroundDrawable in the framework implementation. + @SuppressWarnings("deprecation") + @Override + public void setBackgroundDrawable(Drawable background) { + if (background == this.background) { + return; } - - // All the constructors delegate to this init method. The 3-argument constructor is not - // available in FrameLayout before v11, so call super with the exact same arguments. - private void init(AttributeSet attrs, int defStyleAttr) { - if (attrs != null) { - TypedArray a = getContext().obtainStyledAttributes(attrs, - R.styleable.SuwIllustration, defStyleAttr, 0); - mAspectRatio = a.getFloat(R.styleable.SuwIllustration_suwAspectRatio, 0.0f); - a.recycle(); - } - // Number of pixels of the 8dp baseline grid as defined in material design specs - mBaselineGridSize = getResources().getDisplayMetrics().density * 8; - setWillNotDraw(false); - } - - /** - * The background will be drawn to fill up the rest of the view. It will also be scaled by the - * same amount as the foreground so their textures look the same. - */ - // Override the deprecated setBackgroundDrawable method to support API < 16. View.setBackground - // forwards to setBackgroundDrawable in the framework implementation. - @SuppressWarnings("deprecation") - @Override - public void setBackgroundDrawable(Drawable background) { - if (background == mBackground) { - return; - } - mBackground = background; - invalidate(); - requestLayout(); + this.background = background; + invalidate(); + requestLayout(); + } + + /** + * Sets the drawable used as the illustration. The drawable is expected to have intrinsic width + * and height defined and will be scaled to fit the width of the view. + */ + public void setIllustration(Drawable illustration) { + if (illustration == this.illustration) { + return; } - - /** - * Sets the drawable used as the illustration. The drawable is expected to have intrinsic - * width and height defined and will be scaled to fit the width of the view. - */ - public void setIllustration(Drawable illustration) { - if (illustration == mIllustration) { - return; - } - mIllustration = illustration; - invalidate(); - requestLayout(); + this.illustration = illustration; + invalidate(); + requestLayout(); + } + + /** + * Set the aspect ratio reserved for the illustration. This overrides the top padding of the view + * according to the width of this view and the aspect ratio. Children views will start being laid + * out below this aspect ratio. + * + * @param aspectRatio A float value specifying the aspect ratio (= width / height). 0 to not + * override the top padding. + */ + public void setAspectRatio(float aspectRatio) { + this.aspectRatio = aspectRatio; + invalidate(); + requestLayout(); + } + + @Override + @Deprecated + public void setForeground(Drawable d) { + setIllustration(d); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + if (aspectRatio != 0.0f) { + int parentWidth = MeasureSpec.getSize(widthMeasureSpec); + int illustrationHeight = (int) (parentWidth / aspectRatio); + illustrationHeight = (int) (illustrationHeight - (illustrationHeight % baselineGridSize)); + setPadding(0, illustrationHeight, 0, 0); } - - /** - * Set the aspect ratio reserved for the illustration. This overrides the top padding of the - * view according to the width of this view and the aspect ratio. Children views will start - * being laid out below this aspect ratio. - * - * @param aspectRatio A float value specifying the aspect ratio (= width / height). 0 to not - * override the top padding. - */ - public void setAspectRatio(float aspectRatio) { - mAspectRatio = aspectRatio; - invalidate(); - requestLayout(); + if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { + //noinspection AndroidLintInlinedApi + setOutlineProvider(ViewOutlineProvider.BOUNDS); } - - @Override - @Deprecated - public void setForeground(Drawable d) { - setIllustration(d); + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + final int layoutWidth = right - left; + final int layoutHeight = bottom - top; + if (illustration != null) { + int intrinsicWidth = illustration.getIntrinsicWidth(); + int intrinsicHeight = illustration.getIntrinsicHeight(); + + viewBounds.set(0, 0, layoutWidth, layoutHeight); + if (aspectRatio != 0f) { + scale = layoutWidth / (float) intrinsicWidth; + intrinsicWidth = layoutWidth; + intrinsicHeight = (int) (intrinsicHeight * scale); + } + Gravity.apply( + Gravity.FILL_HORIZONTAL | Gravity.TOP, + intrinsicWidth, + intrinsicHeight, + viewBounds, + illustrationBounds); + illustration.setBounds(illustrationBounds); } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - if (mAspectRatio != 0.0f) { - int parentWidth = MeasureSpec.getSize(widthMeasureSpec); - int illustrationHeight = (int) (parentWidth / mAspectRatio); - illustrationHeight = - (int) (illustrationHeight - (illustrationHeight % mBaselineGridSize)); - setPadding(0, illustrationHeight, 0, 0); - } - if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { - //noinspection AndroidLintInlinedApi - setOutlineProvider(ViewOutlineProvider.BOUNDS); - } - super.onMeasure(widthMeasureSpec, heightMeasureSpec); + if (background != null) { + // Scale the background bounds by the same scale to compensate for the scale done to the + // canvas in onDraw. + background.setBounds( + 0, + 0, + (int) Math.ceil(layoutWidth / scale), + (int) Math.ceil((layoutHeight - illustrationBounds.height()) / scale)); } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - final int layoutWidth = right - left; - final int layoutHeight = bottom - top; - if (mIllustration != null) { - int intrinsicWidth = mIllustration.getIntrinsicWidth(); - int intrinsicHeight = mIllustration.getIntrinsicHeight(); - - mViewBounds.set(0, 0, layoutWidth, layoutHeight); - if (mAspectRatio != 0f) { - mScale = layoutWidth / (float) intrinsicWidth; - intrinsicWidth = layoutWidth; - intrinsicHeight = (int) (intrinsicHeight * mScale); - } - Gravity.apply(Gravity.FILL_HORIZONTAL | Gravity.TOP, intrinsicWidth, - intrinsicHeight, mViewBounds, mIllustrationBounds); - mIllustration.setBounds(mIllustrationBounds); - } - if (mBackground != null) { - // Scale the background bounds by the same scale to compensate for the scale done to the - // canvas in onDraw. - mBackground.setBounds(0, 0, (int) Math.ceil(layoutWidth / mScale), - (int) Math.ceil((layoutHeight - mIllustrationBounds.height()) / mScale)); - } - super.onLayout(changed, left, top, right, bottom); + super.onLayout(changed, left, top, right, bottom); + } + + @Override + public void onDraw(Canvas canvas) { + if (background != null) { + // Draw the background filling parts not covered by the illustration + canvas.save(); + canvas.translate(0, illustrationBounds.height()); + // Scale the background so its size matches the foreground + canvas.scale(scale, scale, 0, 0); + if (VERSION.SDK_INT > VERSION_CODES.JELLY_BEAN_MR1 + && shouldMirrorDrawable(background, getLayoutDirection())) { + // Flip the illustration for RTL layouts + canvas.scale(-1, 1); + canvas.translate(-background.getBounds().width(), 0); + } + background.draw(canvas); + canvas.restore(); } - - @Override - public void onDraw(Canvas canvas) { - if (mBackground != null) { - // Draw the background filling parts not covered by the illustration - canvas.save(); - canvas.translate(0, mIllustrationBounds.height()); - // Scale the background so its size matches the foreground - canvas.scale(mScale, mScale, 0, 0); - if (VERSION.SDK_INT > VERSION_CODES.JELLY_BEAN_MR1 && - shouldMirrorDrawable(mBackground, getLayoutDirection())) { - // Flip the illustration for RTL layouts - canvas.scale(-1, 1); - canvas.translate(-mBackground.getBounds().width(), 0); - } - mBackground.draw(canvas); - canvas.restore(); - } - if (mIllustration != null) { - canvas.save(); - if (VERSION.SDK_INT > VERSION_CODES.JELLY_BEAN_MR1 && - shouldMirrorDrawable(mIllustration, getLayoutDirection())) { - // Flip the illustration for RTL layouts - canvas.scale(-1, 1); - canvas.translate(-mIllustrationBounds.width(), 0); - } - // Draw the illustration - mIllustration.draw(canvas); - canvas.restore(); - } - super.onDraw(canvas); + if (illustration != null) { + canvas.save(); + if (VERSION.SDK_INT > VERSION_CODES.JELLY_BEAN_MR1 + && shouldMirrorDrawable(illustration, getLayoutDirection())) { + // Flip the illustration for RTL layouts + canvas.scale(-1, 1); + canvas.translate(-illustrationBounds.width(), 0); + } + // Draw the illustration + illustration.draw(canvas); + canvas.restore(); } - - private boolean shouldMirrorDrawable(Drawable drawable, int layoutDirection) { - if (layoutDirection == LayoutDirection.RTL) { - if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { - return drawable.isAutoMirrored(); - } else if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) { - final int flags = getContext().getApplicationInfo().flags; - //noinspection AndroidLintInlinedApi - return (flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0; - } - } - return false; + super.onDraw(canvas); + } + + private boolean shouldMirrorDrawable(Drawable drawable, int layoutDirection) { + if (layoutDirection == LayoutDirection.RTL) { + if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { + return drawable.isAutoMirrored(); + } else if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) { + final int flags = getContext().getApplicationInfo().flags; + //noinspection AndroidLintInlinedApi + return (flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0; + } } + return false; + } } diff --git a/library/main/src/com/android/setupwizardlib/view/IllustrationVideoView.java b/library/main/src/com/android/setupwizardlib/view/IllustrationVideoView.java index 53149ea..375ee18 100644 --- a/library/main/src/com/android/setupwizardlib/view/IllustrationVideoView.java +++ b/library/main/src/com/android/setupwizardlib/view/IllustrationVideoView.java @@ -22,18 +22,23 @@ import android.content.res.TypedArray; import android.graphics.SurfaceTexture; import android.graphics.drawable.Animatable; import android.media.MediaPlayer; +import android.media.MediaPlayer.OnErrorListener; +import android.media.MediaPlayer.OnInfoListener; +import android.media.MediaPlayer.OnPreparedListener; +import android.media.MediaPlayer.OnSeekCompleteListener; +import android.net.Uri; import android.os.Build.VERSION_CODES; +import androidx.annotation.Nullable; +import androidx.annotation.RawRes; +import androidx.annotation.VisibleForTesting; import android.util.AttributeSet; import android.util.Log; import android.view.Surface; import android.view.TextureView; +import android.view.TextureView.SurfaceTextureListener; import android.view.View; - -import androidx.annotation.Nullable; -import androidx.annotation.RawRes; -import androidx.annotation.VisibleForTesting; - import com.android.setupwizardlib.R; +import java.io.IOException; /** * A view for displaying videos in a continuous loop (without audio). This is typically used for @@ -44,255 +49,295 @@ import com.android.setupwizardlib.R; * should loop back to * * <p>For optimal file size, use avconv or other video compression tool to remove the unused audio - * track and reduce the size of your video asset: - * avconv -i [input file] -vcodec h264 -crf 20 -an [output_file] + * track and reduce the size of your video asset: avconv -i [input file] -vcodec h264 -crf 20 -an + * [output_file] */ @TargetApi(VERSION_CODES.ICE_CREAM_SANDWICH) -public class IllustrationVideoView extends TextureView implements Animatable, - TextureView.SurfaceTextureListener, - MediaPlayer.OnPreparedListener, - MediaPlayer.OnSeekCompleteListener, - MediaPlayer.OnInfoListener { +public class IllustrationVideoView extends TextureView + implements Animatable, + SurfaceTextureListener, + OnPreparedListener, + OnSeekCompleteListener, + OnInfoListener, + OnErrorListener { - private static final String TAG = "IllustrationVideoView"; + private static final String TAG = "IllustrationVideoView"; - protected float mAspectRatio = 1.0f; // initial guess until we know + protected float mAspectRatio = 1.0f; // initial guess until we know - @Nullable // Can be null when media player fails to initialize - protected MediaPlayer mMediaPlayer; + @Nullable // Can be null when media player fails to initialize + protected MediaPlayer mMediaPlayer; - private @RawRes int mVideoResId = 0; + private @RawRes int videoResId = 0; - @VisibleForTesting Surface mSurface; + private String videoResPackageName; - protected int mWindowVisibility; + @VisibleForTesting Surface surface; - public IllustrationVideoView(Context context, AttributeSet attrs) { - super(context, attrs); - final TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.SuwIllustrationVideoView); - mVideoResId = a.getResourceId(R.styleable.SuwIllustrationVideoView_suwVideo, 0); - a.recycle(); + private boolean prepared; - // By default the video scales without interpolation, resulting in jagged edges in the - // video. This works around it by making the view go through scaling, which will apply - // anti-aliasing effects. - setScaleX(0.9999999f); - setScaleX(0.9999999f); + public IllustrationVideoView(Context context, AttributeSet attrs) { + super(context, attrs); + final TypedArray a = + context.obtainStyledAttributes(attrs, R.styleable.SuwIllustrationVideoView); + final int videoResId = a.getResourceId(R.styleable.SuwIllustrationVideoView_suwVideo, 0); + a.recycle(); + setVideoResource(videoResId); - setSurfaceTextureListener(this); - } + // By default the video scales without interpolation, resulting in jagged edges in the + // video. This works around it by making the view go through scaling, which will apply + // anti-aliasing effects. + setScaleX(0.9999999f); + setScaleX(0.9999999f); - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int width = MeasureSpec.getSize(widthMeasureSpec); - int height = MeasureSpec.getSize(heightMeasureSpec); - - if (height < width * mAspectRatio) { - // Height constraint is tighter. Need to scale down the width to fit aspect ratio. - width = (int) (height / mAspectRatio); - } else { - // Width constraint is tighter. Need to scale down the height to fit aspect ratio. - height = (int) (width * mAspectRatio); - } - - super.onMeasure( - MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); - } + setSurfaceTextureListener(this); + } - /** - * Set the video to be played by this view. - * - * @param resId Resource ID of the video, typically an MP4 under res/raw. - */ - public void setVideoResource(@RawRes int resId) { - if (resId != mVideoResId) { - mVideoResId = resId; - createMediaPlayer(); - } - } + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + int width = MeasureSpec.getSize(widthMeasureSpec); + int height = MeasureSpec.getSize(heightMeasureSpec); - @Override - public void onWindowFocusChanged(boolean hasWindowFocus) { - super.onWindowFocusChanged(hasWindowFocus); - if (hasWindowFocus) { - start(); - } else { - stop(); - } + if (height < width * mAspectRatio) { + // Height constraint is tighter. Need to scale down the width to fit aspect ratio. + width = (int) (height / mAspectRatio); + } else { + // Width constraint is tighter. Need to scale down the height to fit aspect ratio. + height = (int) (width * mAspectRatio); } - /** - * Creates a media player for the current URI. The media player will be started immediately if - * the view's window is visible. If there is an existing media player, it will be released. - */ - protected void createMediaPlayer() { - if (mMediaPlayer != null) { - mMediaPlayer.release(); - } - if (mSurface == null || mVideoResId == 0) { - return; - } - - mMediaPlayer = MediaPlayer.create(getContext(), mVideoResId); - - if (mMediaPlayer != null) { - mMediaPlayer.setSurface(mSurface); - mMediaPlayer.setOnPreparedListener(this); - mMediaPlayer.setOnSeekCompleteListener(this); - mMediaPlayer.setOnInfoListener(this); - - float aspectRatio = - (float) mMediaPlayer.getVideoHeight() / mMediaPlayer.getVideoWidth(); - if (mAspectRatio != aspectRatio) { - mAspectRatio = aspectRatio; - requestLayout(); - } - } else { - Log.wtf(TAG, "Unable to initialize media player for video view"); - } - if (mWindowVisibility == View.VISIBLE) { - start(); - } + super.onMeasure( + MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); + } + + /** + * Set the video and video package name to be played by this view. + * + * @param videoResId Resource ID of the video, typically an MP4 under res/raw. + * @param videoResPackageName The package name of videoResId. + */ + public void setVideoResource(@RawRes int videoResId, String videoResPackageName) { + if (videoResId != this.videoResId + || (videoResPackageName != null && !videoResPackageName.equals(this.videoResPackageName))) { + this.videoResId = videoResId; + this.videoResPackageName = videoResPackageName; + createMediaPlayer(); } - - protected void createSurface() { - if (mSurface != null) { - mSurface.release(); - mSurface = null; - } - // Reattach only if it has been previously released - SurfaceTexture surfaceTexture = getSurfaceTexture(); - if (surfaceTexture != null) { - setVisibility(View.INVISIBLE); - mSurface = new Surface(surfaceTexture); - } + } + + /** + * Set the video to be played by this view. + * + * @param resId Resource ID of the video, typically an MP4 under res/raw. + */ + public void setVideoResource(@RawRes int resId) { + setVideoResource(resId, getContext().getPackageName()); + } + + @Override + public void onWindowFocusChanged(boolean hasWindowFocus) { + super.onWindowFocusChanged(hasWindowFocus); + if (hasWindowFocus) { + start(); + } else { + stop(); } - - @Override - protected void onWindowVisibilityChanged(int visibility) { - super.onWindowVisibilityChanged(visibility); - mWindowVisibility = visibility; - if (visibility == View.VISIBLE) { - reattach(); - } else { - release(); - } + } + + /** + * Creates a media player for the current URI. The media player will be started immediately if the + * view's window is visible. If there is an existing media player, it will be released. + */ + protected void createMediaPlayer() { + if (mMediaPlayer != null) { + mMediaPlayer.release(); } - - /** - * Whether the media player should play the video in a continuous loop. The default value is - * true. - */ - protected boolean shouldLoop() { - return true; + if (surface == null || videoResId == 0) { + return; } - /** - * Release any resources used by this view. This is automatically called in - * onSurfaceTextureDestroyed so in most cases you don't have to call this. - */ - public void release() { - if (mMediaPlayer != null) { - mMediaPlayer.stop(); - mMediaPlayer.release(); - mMediaPlayer = null; - } - if (mSurface != null) { - mSurface.release(); - mSurface = null; - } + mMediaPlayer = new MediaPlayer(); + + mMediaPlayer.setSurface(surface); + mMediaPlayer.setOnPreparedListener(this); + mMediaPlayer.setOnSeekCompleteListener(this); + mMediaPlayer.setOnInfoListener(this); + mMediaPlayer.setOnErrorListener(this); + + setVideoResourceInternal(videoResId, videoResPackageName); + } + + private void setVideoResourceInternal(@RawRes int videoRes, String videoResPackageName) { + Uri uri = Uri.parse("android.resource://" + videoResPackageName + "/" + videoRes); + try { + mMediaPlayer.setDataSource(getContext(), uri, null); + mMediaPlayer.prepareAsync(); + } catch (IOException e) { + Log.wtf(TAG, "Unable to set data source", e); } + } - private void reattach() { - if (mSurface == null) { - initVideo(); - } + protected void createSurface() { + if (surface != null) { + surface.release(); + surface = null; + } + // Reattach only if it has been previously released + SurfaceTexture surfaceTexture = getSurfaceTexture(); + if (surfaceTexture != null) { + setVisibility(View.INVISIBLE); + surface = new Surface(surfaceTexture); } + } + + @Override + protected void onWindowVisibilityChanged(int visibility) { + super.onWindowVisibilityChanged(visibility); + if (visibility == View.VISIBLE) { + reattach(); + } else { + release(); + } + } + + /** + * Whether the media player should play the video in a continuous loop. The default value is true. + */ + protected boolean shouldLoop() { + return true; + } + + /** + * Release any resources used by this view. This is automatically called in + * onSurfaceTextureDestroyed so in most cases you don't have to call this. + */ + public void release() { + if (mMediaPlayer != null) { + mMediaPlayer.release(); + mMediaPlayer = null; + prepared = false; + } + if (surface != null) { + surface.release(); + surface = null; + } + } - private void initVideo() { - if (mWindowVisibility != View.VISIBLE) { - return; - } - createSurface(); - if (mSurface != null) { - createMediaPlayer(); - } else { - Log.w("IllustrationVideoView", "Surface creation failed"); - } + private void reattach() { + if (surface == null) { + initVideo(); } + } - protected void onRenderingStart() { + private void initVideo() { + if (getWindowVisibility() != View.VISIBLE) { + return; } + createSurface(); + if (surface != null) { + createMediaPlayer(); + } else { + Log.w(TAG, "Surface creation failed"); + } + } - /* SurfaceTextureListener methods */ + protected void onRenderingStart() {} - @Override - public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { - // Keep the view hidden until video starts - setVisibility(View.INVISIBLE); - initVideo(); - } + /* SurfaceTextureListener methods */ - @Override - public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) { - } + @Override + public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { + // Keep the view hidden until video starts + setVisibility(View.INVISIBLE); + initVideo(); + } - @Override - public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { - release(); - return true; - } + @Override + public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {} - @Override - public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { - } + @Override + public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { + release(); + return true; + } - /* Animatable methods */ + @Override + public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {} - @Override - public void start() { - if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) { - mMediaPlayer.start(); - } - } + /* Animatable methods */ - @Override - public void stop() { - if (mMediaPlayer != null) { - mMediaPlayer.pause(); - } + @Override + public void start() { + if (prepared && mMediaPlayer != null && !mMediaPlayer.isPlaying()) { + mMediaPlayer.start(); } + } - @Override - public boolean isRunning() { - return mMediaPlayer != null && mMediaPlayer.isPlaying(); + @Override + public void stop() { + if (prepared && mMediaPlayer != null) { + mMediaPlayer.pause(); } + } - /* MediaPlayer callbacks */ + @Override + public boolean isRunning() { + return mMediaPlayer != null && mMediaPlayer.isPlaying(); + } - @Override - public boolean onInfo(MediaPlayer mp, int what, int extra) { - if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) { - // Video available, show view now - setVisibility(View.VISIBLE); - onRenderingStart(); - } - return false; - } + /* MediaPlayer callbacks */ - @Override - public void onPrepared(MediaPlayer mp) { - mp.setLooping(shouldLoop()); + @Override + public boolean onInfo(MediaPlayer mp, int what, int extra) { + if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) { + // Video available, show view now + setVisibility(View.VISIBLE); + onRenderingStart(); } - - @Override - public void onSeekComplete(MediaPlayer mp) { - mp.start(); + return false; + } + + @Override + public void onPrepared(MediaPlayer mp) { + prepared = true; + mp.setLooping(shouldLoop()); + + float aspectRatio = 0.0f; + if (mp.getVideoWidth() > 0 && mp.getVideoHeight() > 0) { + aspectRatio = (float) mp.getVideoHeight() / mp.getVideoWidth(); + } else { + Log.w(TAG, "Unexpected video size=" + mp.getVideoWidth() + "x" + mp.getVideoHeight()); } - - public int getCurrentPosition() { - return mMediaPlayer == null ? 0 : mMediaPlayer.getCurrentPosition(); + if (Float.compare(mAspectRatio, aspectRatio) != 0) { + mAspectRatio = aspectRatio; + requestLayout(); + } + if (getWindowVisibility() == View.VISIBLE) { + start(); } + } + + @Override + public void onSeekComplete(MediaPlayer mp) { + if (isPrepared()) { + mp.start(); + } else { + Log.wtf(TAG, "Seek complete but media player not prepared"); + } + } + + public int getCurrentPosition() { + return mMediaPlayer == null ? 0 : mMediaPlayer.getCurrentPosition(); + } + + protected boolean isPrepared() { + return prepared; + } + + @Override + public boolean onError(MediaPlayer mediaPlayer, int what, int extra) { + Log.w(TAG, "MediaPlayer error. what=" + what + " extra=" + extra); + return false; + } } diff --git a/library/main/src/com/android/setupwizardlib/view/IntrinsicSizeFrameLayout.java b/library/main/src/com/android/setupwizardlib/view/IntrinsicSizeFrameLayout.java index 02fdcc7..c6a38f6 100644 --- a/library/main/src/com/android/setupwizardlib/view/IntrinsicSizeFrameLayout.java +++ b/library/main/src/com/android/setupwizardlib/view/IntrinsicSizeFrameLayout.java @@ -22,71 +22,71 @@ import android.content.res.TypedArray; import android.os.Build.VERSION_CODES; import android.util.AttributeSet; import android.widget.FrameLayout; - import com.android.setupwizardlib.R; /** * A FrameLayout subclass that has an "intrinsic size", which is the size it wants to be if that is - * within the constraints given by the parent. The intrinsic size can be set with the - * {@code android:width} and {@code android:height} attributes in XML. + * within the constraints given by the parent. The intrinsic size can be set with the {@code + * android:width} and {@code android:height} attributes in XML. * - * Note that for the intrinsic size to be meaningful, {@code android:layout_width} and/or - * {@code android:layout_height} will need to be {@code wrap_content}. + * <p>Note that for the intrinsic size to be meaningful, {@code android:layout_width} and/or {@code + * android:layout_height} will need to be {@code wrap_content}. */ public class IntrinsicSizeFrameLayout extends FrameLayout { - private int mIntrinsicHeight = 0; - private int mIntrinsicWidth = 0; + private int intrinsicHeight = 0; + private int intrinsicWidth = 0; - public IntrinsicSizeFrameLayout(Context context) { - super(context); - init(context, null, 0); - } + public IntrinsicSizeFrameLayout(Context context) { + super(context); + init(context, null, 0); + } - public IntrinsicSizeFrameLayout(Context context, AttributeSet attrs) { - super(context, attrs); - init(context, attrs, 0); - } + public IntrinsicSizeFrameLayout(Context context, AttributeSet attrs) { + super(context, attrs); + init(context, attrs, 0); + } - @TargetApi(VERSION_CODES.HONEYCOMB) - public IntrinsicSizeFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(context, attrs, defStyleAttr); - } + @TargetApi(VERSION_CODES.HONEYCOMB) + public IntrinsicSizeFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(context, attrs, defStyleAttr); + } - private void init(Context context, AttributeSet attrs, int defStyleAttr) { - final TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.SuwIntrinsicSizeFrameLayout, defStyleAttr, 0); - mIntrinsicHeight = - a.getDimensionPixelSize(R.styleable.SuwIntrinsicSizeFrameLayout_android_height, 0); - mIntrinsicWidth = - a.getDimensionPixelSize(R.styleable.SuwIntrinsicSizeFrameLayout_android_width, 0); - a.recycle(); - } + private void init(Context context, AttributeSet attrs, int defStyleAttr) { + final TypedArray a = + context.obtainStyledAttributes( + attrs, R.styleable.SuwIntrinsicSizeFrameLayout, defStyleAttr, 0); + intrinsicHeight = + a.getDimensionPixelSize(R.styleable.SuwIntrinsicSizeFrameLayout_android_height, 0); + intrinsicWidth = + a.getDimensionPixelSize(R.styleable.SuwIntrinsicSizeFrameLayout_android_width, 0); + a.recycle(); + } - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(getIntrinsicMeasureSpec(widthMeasureSpec, mIntrinsicWidth), - getIntrinsicMeasureSpec(heightMeasureSpec, mIntrinsicHeight)); - } + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure( + getIntrinsicMeasureSpec(widthMeasureSpec, intrinsicWidth), + getIntrinsicMeasureSpec(heightMeasureSpec, intrinsicHeight)); + } - private int getIntrinsicMeasureSpec(int measureSpec, int intrinsicSize) { - if (intrinsicSize <= 0) { - // Intrinsic size is not set, just return the original spec - return measureSpec; - } - final int mode = MeasureSpec.getMode(measureSpec); - final int size = MeasureSpec.getSize(measureSpec); - if (mode == MeasureSpec.UNSPECIFIED) { - // Parent did not give any constraint, so we'll be the intrinsic size - return MeasureSpec.makeMeasureSpec(mIntrinsicHeight, MeasureSpec.EXACTLY); - } else if (mode == MeasureSpec.AT_MOST) { - // If intrinsic size is within parents constraint, take the intrinsic size. - // Otherwise take the parents size because that's closest to the intrinsic size. - return MeasureSpec.makeMeasureSpec(Math.min(size, mIntrinsicHeight), - MeasureSpec.EXACTLY); - } - // Parent specified EXACTLY, or in all other cases, just return the original spec - return measureSpec; + private int getIntrinsicMeasureSpec(int measureSpec, int intrinsicSize) { + if (intrinsicSize <= 0) { + // Intrinsic size is not set, just return the original spec + return measureSpec; + } + final int mode = MeasureSpec.getMode(measureSpec); + final int size = MeasureSpec.getSize(measureSpec); + if (mode == MeasureSpec.UNSPECIFIED) { + // Parent did not give any constraint, so we'll be the intrinsic size + return MeasureSpec.makeMeasureSpec(intrinsicHeight, MeasureSpec.EXACTLY); + } else if (mode == MeasureSpec.AT_MOST) { + // If intrinsic size is within parents constraint, take the intrinsic size. + // Otherwise take the parents size because that's closest to the intrinsic size. + return MeasureSpec.makeMeasureSpec(Math.min(size, intrinsicHeight), MeasureSpec.EXACTLY); } + // Parent specified EXACTLY, or in all other cases, just return the original spec + return measureSpec; + } } diff --git a/library/main/src/com/android/setupwizardlib/view/NavigationBar.java b/library/main/src/com/android/setupwizardlib/view/NavigationBar.java index 9971bac..1044e56 100644 --- a/library/main/src/com/android/setupwizardlib/view/NavigationBar.java +++ b/library/main/src/com/android/setupwizardlib/view/NavigationBar.java @@ -21,14 +21,12 @@ import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.os.Build.VERSION_CODES; +import androidx.annotation.StyleableRes; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; - -import androidx.annotation.StyleableRes; - import com.android.setupwizardlib.R; /** @@ -40,104 +38,105 @@ import com.android.setupwizardlib.R; */ public class NavigationBar extends LinearLayout implements View.OnClickListener { - /** - * An interface to listen to events of the navigation bar, namely when the user clicks on the - * back or next button. - */ - public interface NavigationBarListener { - void onNavigateBack(); - void onNavigateNext(); + /** + * An interface to listen to events of the navigation bar, namely when the user clicks on the back + * or next button. + */ + public interface NavigationBarListener { + void onNavigateBack(); + + void onNavigateNext(); + } + + private static int getNavbarTheme(Context context) { + // Normally we can automatically guess the theme by comparing the foreground color against + // the background color. But we also allow specifying explicitly using suwNavBarTheme. + TypedArray attributes = + context.obtainStyledAttributes( + new int[] { + R.attr.suwNavBarTheme, android.R.attr.colorForeground, android.R.attr.colorBackground + }); + @StyleableRes int suwNavBarTheme = 0; + @StyleableRes int colorForeground = 1; + @StyleableRes int colorBackground = 2; + int theme = attributes.getResourceId(suwNavBarTheme, 0); + if (theme == 0) { + // Compare the value of the foreground against the background color to see if current + // theme is light-on-dark or dark-on-light. + float[] foregroundHsv = new float[3]; + float[] backgroundHsv = new float[3]; + Color.colorToHSV(attributes.getColor(colorForeground, 0), foregroundHsv); + Color.colorToHSV(attributes.getColor(colorBackground, 0), backgroundHsv); + boolean isDarkBg = foregroundHsv[2] > backgroundHsv[2]; + theme = isDarkBg ? R.style.SuwNavBarThemeDark : R.style.SuwNavBarThemeLight; } - - private static int getNavbarTheme(Context context) { - // Normally we can automatically guess the theme by comparing the foreground color against - // the background color. But we also allow specifying explicitly using suwNavBarTheme. - TypedArray attributes = context.obtainStyledAttributes( - new int[] { - R.attr.suwNavBarTheme, - android.R.attr.colorForeground, - android.R.attr.colorBackground }); - @StyleableRes int suwNavBarTheme = 0; - @StyleableRes int colorForeground = 1; - @StyleableRes int colorBackground = 2; - int theme = attributes.getResourceId(suwNavBarTheme, 0); - if (theme == 0) { - // Compare the value of the foreground against the background color to see if current - // theme is light-on-dark or dark-on-light. - float[] foregroundHsv = new float[3]; - float[] backgroundHsv = new float[3]; - Color.colorToHSV(attributes.getColor(colorForeground, 0), foregroundHsv); - Color.colorToHSV(attributes.getColor(colorBackground, 0), backgroundHsv); - boolean isDarkBg = foregroundHsv[2] > backgroundHsv[2]; - theme = isDarkBg ? R.style.SuwNavBarThemeDark : R.style.SuwNavBarThemeLight; - } - attributes.recycle(); - return theme; - } - - private static Context getThemedContext(Context context) { - final int theme = getNavbarTheme(context); - return new ContextThemeWrapper(context, theme); + attributes.recycle(); + return theme; + } + + private static Context getThemedContext(Context context) { + final int theme = getNavbarTheme(context); + return new ContextThemeWrapper(context, theme); + } + + private Button nextButton; + private Button backButton; + private Button moreButton; + private NavigationBarListener listener; + + public NavigationBar(Context context) { + super(getThemedContext(context)); + init(); + } + + public NavigationBar(Context context, AttributeSet attrs) { + super(getThemedContext(context), attrs); + init(); + } + + @TargetApi(VERSION_CODES.HONEYCOMB) + public NavigationBar(Context context, AttributeSet attrs, int defStyleAttr) { + super(getThemedContext(context), attrs, defStyleAttr); + init(); + } + + // All the constructors delegate to this init method. The 3-argument constructor is not + // available in LinearLayout before v11, so call super with the exact same arguments. + private void init() { + View.inflate(getContext(), R.layout.suw_navbar_view, this); + nextButton = (Button) findViewById(R.id.suw_navbar_next); + backButton = (Button) findViewById(R.id.suw_navbar_back); + moreButton = (Button) findViewById(R.id.suw_navbar_more); + } + + public Button getBackButton() { + return backButton; + } + + public Button getNextButton() { + return nextButton; + } + + public Button getMoreButton() { + return moreButton; + } + + public void setNavigationBarListener(NavigationBarListener listener) { + this.listener = listener; + if (this.listener != null) { + getBackButton().setOnClickListener(this); + getNextButton().setOnClickListener(this); } - - private Button mNextButton; - private Button mBackButton; - private Button mMoreButton; - private NavigationBarListener mListener; - - public NavigationBar(Context context) { - super(getThemedContext(context)); - init(); - } - - public NavigationBar(Context context, AttributeSet attrs) { - super(getThemedContext(context), attrs); - init(); - } - - @TargetApi(VERSION_CODES.HONEYCOMB) - public NavigationBar(Context context, AttributeSet attrs, int defStyleAttr) { - super(getThemedContext(context), attrs, defStyleAttr); - init(); - } - - // All the constructors delegate to this init method. The 3-argument constructor is not - // available in LinearLayout before v11, so call super with the exact same arguments. - private void init() { - View.inflate(getContext(), R.layout.suw_navbar_view, this); - mNextButton = (Button) findViewById(R.id.suw_navbar_next); - mBackButton = (Button) findViewById(R.id.suw_navbar_back); - mMoreButton = (Button) findViewById(R.id.suw_navbar_more); - } - - public Button getBackButton() { - return mBackButton; - } - - public Button getNextButton() { - return mNextButton; - } - - public Button getMoreButton() { - return mMoreButton; - } - - public void setNavigationBarListener(NavigationBarListener listener) { - mListener = listener; - if (mListener != null) { - getBackButton().setOnClickListener(this); - getNextButton().setOnClickListener(this); - } - } - - @Override - public void onClick(View view) { - if (mListener != null) { - if (view == getBackButton()) { - mListener.onNavigateBack(); - } else if (view == getNextButton()) { - mListener.onNavigateNext(); - } - } + } + + @Override + public void onClick(View view) { + if (listener != null) { + if (view == getBackButton()) { + listener.onNavigateBack(); + } else if (view == getNextButton()) { + listener.onNavigateNext(); + } } + } } diff --git a/library/main/src/com/android/setupwizardlib/view/StatusBarBackgroundLayout.java b/library/main/src/com/android/setupwizardlib/view/StatusBarBackgroundLayout.java index fe0bc8f..dd8c27f 100644 --- a/library/main/src/com/android/setupwizardlib/view/StatusBarBackgroundLayout.java +++ b/library/main/src/com/android/setupwizardlib/view/StatusBarBackgroundLayout.java @@ -26,7 +26,6 @@ import android.os.Build.VERSION_CODES; import android.util.AttributeSet; import android.view.WindowInsets; import android.widget.FrameLayout; - import com.android.setupwizardlib.R; /** @@ -40,74 +39,75 @@ import com.android.setupwizardlib.R; */ public class StatusBarBackgroundLayout extends FrameLayout { - private Drawable mStatusBarBackground; - private Object mLastInsets; // Use generic Object type for compatibility + private Drawable statusBarBackground; + private Object lastInsets; // Use generic Object type for compatibility - public StatusBarBackgroundLayout(Context context) { - super(context); - init(context, null, 0); - } + public StatusBarBackgroundLayout(Context context) { + super(context); + init(context, null, 0); + } - public StatusBarBackgroundLayout(Context context, AttributeSet attrs) { - super(context, attrs); - init(context, attrs, 0); - } + public StatusBarBackgroundLayout(Context context, AttributeSet attrs) { + super(context, attrs); + init(context, attrs, 0); + } - @TargetApi(VERSION_CODES.HONEYCOMB) - public StatusBarBackgroundLayout(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(context, attrs, defStyleAttr); - } + @TargetApi(VERSION_CODES.HONEYCOMB) + public StatusBarBackgroundLayout(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(context, attrs, defStyleAttr); + } - private void init(Context context, AttributeSet attrs, int defStyleAttr) { - final TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.SuwStatusBarBackgroundLayout, defStyleAttr, 0); - final Drawable statusBarBackground = - a.getDrawable(R.styleable.SuwStatusBarBackgroundLayout_suwStatusBarBackground); - setStatusBarBackground(statusBarBackground); - a.recycle(); - } + private void init(Context context, AttributeSet attrs, int defStyleAttr) { + final TypedArray a = + context.obtainStyledAttributes( + attrs, R.styleable.SuwStatusBarBackgroundLayout, defStyleAttr, 0); + final Drawable statusBarBackground = + a.getDrawable(R.styleable.SuwStatusBarBackgroundLayout_suwStatusBarBackground); + setStatusBarBackground(statusBarBackground); + a.recycle(); + } - @Override - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { - if (mLastInsets == null) { - requestApplyInsets(); - } - } + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { + if (lastInsets == null) { + requestApplyInsets(); + } } + } - @Override - protected void onDraw(Canvas canvas) { - super.onDraw(canvas); - if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { - if (mLastInsets != null) { - final int insetTop = ((WindowInsets) mLastInsets).getSystemWindowInsetTop(); - if (insetTop > 0) { - mStatusBarBackground.setBounds(0, 0, getWidth(), insetTop); - mStatusBarBackground.draw(canvas); - } - } + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { + if (lastInsets != null) { + final int insetTop = ((WindowInsets) lastInsets).getSystemWindowInsetTop(); + if (insetTop > 0) { + statusBarBackground.setBounds(0, 0, getWidth(), insetTop); + statusBarBackground.draw(canvas); } + } } + } - public void setStatusBarBackground(Drawable background) { - mStatusBarBackground = background; - if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { - setWillNotDraw(background == null); - setFitsSystemWindows(background != null); - invalidate(); - } + public void setStatusBarBackground(Drawable background) { + statusBarBackground = background; + if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { + setWillNotDraw(background == null); + setFitsSystemWindows(background != null); + invalidate(); } + } - public Drawable getStatusBarBackground() { - return mStatusBarBackground; - } + public Drawable getStatusBarBackground() { + return statusBarBackground; + } - @Override - public WindowInsets onApplyWindowInsets(WindowInsets insets) { - mLastInsets = insets; - return super.onApplyWindowInsets(insets); - } + @Override + public WindowInsets onApplyWindowInsets(WindowInsets insets) { + lastInsets = insets; + return super.onApplyWindowInsets(insets); + } } diff --git a/library/main/src/com/android/setupwizardlib/view/StickyHeaderListView.java b/library/main/src/com/android/setupwizardlib/view/StickyHeaderListView.java index 58274f6..c226f29 100644 --- a/library/main/src/com/android/setupwizardlib/view/StickyHeaderListView.java +++ b/library/main/src/com/android/setupwizardlib/view/StickyHeaderListView.java @@ -29,7 +29,6 @@ import android.view.View; import android.view.WindowInsets; import android.view.accessibility.AccessibilityEvent; import android.widget.ListView; - import com.android.setupwizardlib.R; /** @@ -39,125 +38,129 @@ import com.android.setupwizardlib.R; * when the sticky element hits the top of the view. * * <p>There are a few things to note: + * * <ol> * <li>The two supported scenarios are StickyHeaderListView -> Header (stickyContainer) -> sticky, - * and StickyHeaderListView -> Header (sticky). The arrow (->) represents parent/child - * relationship and must be immediate child. + * and StickyHeaderListView -> Header (sticky). The arrow (->) represents parent/child + * relationship and must be immediate child. * <li>The view does not work well with padding. b/16190933 * <li>If fitsSystemWindows is true, then this will offset the sticking position by the height of - * the system decorations at the top of the screen. + * the system decorations at the top of the screen. * </ol> * * @see StickyHeaderScrollView */ public class StickyHeaderListView extends ListView { - private View mSticky; - private View mStickyContainer; - private int mStatusBarInset = 0; - private RectF mStickyRect = new RectF(); - - public StickyHeaderListView(Context context) { - super(context); - init(null, android.R.attr.listViewStyle); + private View sticky; + private View stickyContainer; + private int statusBarInset = 0; + private final RectF stickyRect = new RectF(); + + public StickyHeaderListView(Context context) { + super(context); + init(null, android.R.attr.listViewStyle); + } + + public StickyHeaderListView(Context context, AttributeSet attrs) { + super(context, attrs); + init(attrs, android.R.attr.listViewStyle); + } + + public StickyHeaderListView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(attrs, defStyleAttr); + } + + private void init(AttributeSet attrs, int defStyleAttr) { + final TypedArray a = + getContext() + .obtainStyledAttributes(attrs, R.styleable.SuwStickyHeaderListView, defStyleAttr, 0); + int headerResId = a.getResourceId(R.styleable.SuwStickyHeaderListView_suwHeader, 0); + if (headerResId != 0) { + LayoutInflater inflater = LayoutInflater.from(getContext()); + View header = inflater.inflate(headerResId, this, false); + addHeaderView(header, null, false); } - - public StickyHeaderListView(Context context, AttributeSet attrs) { - super(context, attrs); - init(attrs, android.R.attr.listViewStyle); + a.recycle(); + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + super.onLayout(changed, l, t, r, b); + if (sticky == null) { + updateStickyView(); } - - public StickyHeaderListView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(attrs, defStyleAttr); + } + + public void updateStickyView() { + sticky = findViewWithTag("sticky"); + stickyContainer = findViewWithTag("stickyContainer"); + } + + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + if (stickyRect.contains(ev.getX(), ev.getY())) { + ev.offsetLocation(-stickyRect.left, -stickyRect.top); + return stickyContainer.dispatchTouchEvent(ev); + } else { + return super.dispatchTouchEvent(ev); } - - private void init(AttributeSet attrs, int defStyleAttr) { - final TypedArray a = getContext().obtainStyledAttributes(attrs, - R.styleable.SuwStickyHeaderListView, defStyleAttr, 0); - int headerResId = a.getResourceId(R.styleable.SuwStickyHeaderListView_suwHeader, 0); - if (headerResId != 0) { - LayoutInflater inflater = LayoutInflater.from(getContext()); - View header = inflater.inflate(headerResId, this, false); - addHeaderView(header, null, false); - } - a.recycle(); - } - - @Override - protected void onLayout(boolean changed, int l, int t, int r, int b) { - super.onLayout(changed, l, t, r, b); - if (mSticky == null) { - updateStickyView(); - } + } + + @Override + public void draw(Canvas canvas) { + super.draw(canvas); + if (sticky != null) { + final int saveCount = canvas.save(); + // The view to draw when sticking to the top + final View drawTarget = stickyContainer != null ? stickyContainer : sticky; + // The offset to draw the view at when sticky + final int drawOffset = stickyContainer != null ? sticky.getTop() : 0; + // Position of the draw target, relative to the outside of the scrollView + final int drawTop = drawTarget.getTop(); + if (drawTop + drawOffset < statusBarInset || !drawTarget.isShown()) { + // ListView does not translate the canvas, so we can simply draw at the top + stickyRect.set( + 0, + -drawOffset + statusBarInset, + drawTarget.getWidth(), + drawTarget.getHeight() - drawOffset + statusBarInset); + canvas.translate(0, stickyRect.top); + canvas.clipRect(0, 0, drawTarget.getWidth(), drawTarget.getHeight()); + drawTarget.draw(canvas); + } else { + stickyRect.setEmpty(); + } + canvas.restoreToCount(saveCount); } - - public void updateStickyView() { - mSticky = findViewWithTag("sticky"); - mStickyContainer = findViewWithTag("stickyContainer"); + } + + @Override + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public WindowInsets onApplyWindowInsets(WindowInsets insets) { + if (getFitsSystemWindows()) { + statusBarInset = insets.getSystemWindowInsetTop(); + insets.replaceSystemWindowInsets( + insets.getSystemWindowInsetLeft(), + 0, /* top */ + insets.getSystemWindowInsetRight(), + insets.getSystemWindowInsetBottom()); } - - @Override - public boolean dispatchTouchEvent(MotionEvent ev) { - if (mStickyRect.contains(ev.getX(), ev.getY())) { - ev.offsetLocation(-mStickyRect.left, -mStickyRect.top); - return mStickyContainer.dispatchTouchEvent(ev); - } else { - return super.dispatchTouchEvent(ev); - } - } - - @Override - public void draw(Canvas canvas) { - super.draw(canvas); - if (mSticky != null) { - final int saveCount = canvas.save(); - // The view to draw when sticking to the top - final View drawTarget = mStickyContainer != null ? mStickyContainer : mSticky; - // The offset to draw the view at when sticky - final int drawOffset = mStickyContainer != null ? mSticky.getTop() : 0; - // Position of the draw target, relative to the outside of the scrollView - final int drawTop = drawTarget.getTop(); - if (drawTop + drawOffset < mStatusBarInset || !drawTarget.isShown()) { - // ListView does not translate the canvas, so we can simply draw at the top - mStickyRect.set(0, -drawOffset + mStatusBarInset, drawTarget.getWidth(), - drawTarget.getHeight() - drawOffset + mStatusBarInset); - canvas.translate(0, mStickyRect.top); - canvas.clipRect(0, 0, drawTarget.getWidth(), drawTarget.getHeight()); - drawTarget.draw(canvas); - } else { - mStickyRect.setEmpty(); - } - canvas.restoreToCount(saveCount); - } - } - - @Override - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - public WindowInsets onApplyWindowInsets(WindowInsets insets) { - if (getFitsSystemWindows()) { - mStatusBarInset = insets.getSystemWindowInsetTop(); - insets.replaceSystemWindowInsets( - insets.getSystemWindowInsetLeft(), - 0, /* top */ - insets.getSystemWindowInsetRight(), - insets.getSystemWindowInsetBottom() - ); - } - return insets; - } - - @Override - public void onInitializeAccessibilityEvent(AccessibilityEvent event) { - super.onInitializeAccessibilityEvent(event); - - // Decoration-only headers should not count as an item for accessibility, adjust the - // accessibility event to account for that. - final int numberOfHeaders = mSticky != null ? 1 : 0; - event.setItemCount(event.getItemCount() - numberOfHeaders); - event.setFromIndex(Math.max(event.getFromIndex() - numberOfHeaders, 0)); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - event.setToIndex(Math.max(event.getToIndex() - numberOfHeaders, 0)); - } + return insets; + } + + @Override + public void onInitializeAccessibilityEvent(AccessibilityEvent event) { + super.onInitializeAccessibilityEvent(event); + + // Decoration-only headers should not count as an item for accessibility, adjust the + // accessibility event to account for that. + final int numberOfHeaders = sticky != null ? 1 : 0; + event.setItemCount(event.getItemCount() - numberOfHeaders); + event.setFromIndex(Math.max(event.getFromIndex() - numberOfHeaders, 0)); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { + event.setToIndex(Math.max(event.getToIndex() - numberOfHeaders, 0)); } + } } diff --git a/library/main/src/com/android/setupwizardlib/view/StickyHeaderScrollView.java b/library/main/src/com/android/setupwizardlib/view/StickyHeaderScrollView.java index ca47446..9fd7b0c 100644 --- a/library/main/src/com/android/setupwizardlib/view/StickyHeaderScrollView.java +++ b/library/main/src/com/android/setupwizardlib/view/StickyHeaderScrollView.java @@ -30,12 +30,13 @@ import android.view.WindowInsets; * drawn when the sticky element hits the top of the view. * * <p>There are a few things to note: + * * <ol> * <li>The two supported scenarios are StickyHeaderScrollView -> subview (stickyContainer) -> - * sticky, and StickyHeaderScrollView -> container -> subview (sticky). - * The arrow (->) represents parent/child relationship and must be immediate child. + * sticky, and StickyHeaderScrollView -> container -> subview (sticky). The arrow (->) + * represents parent/child relationship and must be immediate child. * <li>If fitsSystemWindows is true, then this will offset the sticking position by the height of - * the system decorations at the top of the screen. + * the system decorations at the top of the screen. * <li>For versions before Honeycomb, this will behave like a regular ScrollView. * </ol> * @@ -43,75 +44,75 @@ import android.view.WindowInsets; */ public class StickyHeaderScrollView extends BottomScrollView { - private View mSticky; - private View mStickyContainer; - private int mStatusBarInset = 0; + private View sticky; + private View stickyContainer; + private int statusBarInset = 0; - public StickyHeaderScrollView(Context context) { - super(context); - } + public StickyHeaderScrollView(Context context) { + super(context); + } - public StickyHeaderScrollView(Context context, AttributeSet attrs) { - super(context, attrs); - } + public StickyHeaderScrollView(Context context, AttributeSet attrs) { + super(context, attrs); + } - public StickyHeaderScrollView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } + public StickyHeaderScrollView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } - @Override - protected void onLayout(boolean changed, int l, int t, int r, int b) { - super.onLayout(changed, l, t, r, b); - if (mSticky == null) { - updateStickyView(); - } - updateStickyHeaderPosition(); + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + super.onLayout(changed, l, t, r, b); + if (sticky == null) { + updateStickyView(); } + updateStickyHeaderPosition(); + } - public void updateStickyView() { - mSticky = findViewWithTag("sticky"); - mStickyContainer = findViewWithTag("stickyContainer"); - } + public void updateStickyView() { + sticky = findViewWithTag("sticky"); + stickyContainer = findViewWithTag("stickyContainer"); + } - private void updateStickyHeaderPosition() { - // Note: for pre-Honeycomb the header will not be moved, so this ScrollView essentially - // behaves like a normal BottomScrollView. - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { - if (mSticky != null) { - // The view to draw when sticking to the top - final View drawTarget = mStickyContainer != null ? mStickyContainer : mSticky; - // The offset to draw the view at when sticky - final int drawOffset = mStickyContainer != null ? mSticky.getTop() : 0; - // Position of the draw target, relative to the outside of the scrollView - final int drawTop = drawTarget.getTop() - getScrollY(); - if (drawTop + drawOffset < mStatusBarInset || !drawTarget.isShown()) { - // ScrollView translates the whole canvas so we have to compensate for that - drawTarget.setTranslationY(getScrollY() - drawOffset); - } else { - drawTarget.setTranslationY(0); - } - } + private void updateStickyHeaderPosition() { + // Note: for pre-Honeycomb the header will not be moved, so this ScrollView essentially + // behaves like a normal BottomScrollView. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + if (sticky != null) { + // The view to draw when sticking to the top + final View drawTarget = stickyContainer != null ? stickyContainer : sticky; + // The offset to draw the view at when sticky + final int drawOffset = stickyContainer != null ? sticky.getTop() : 0; + // Position of the draw target, relative to the outside of the scrollView + final int drawTop = drawTarget.getTop() - getScrollY(); + if (drawTop + drawOffset < statusBarInset || !drawTarget.isShown()) { + // ScrollView translates the whole canvas so we have to compensate for that + drawTarget.setTranslationY(getScrollY() - drawOffset); + } else { + drawTarget.setTranslationY(0); } + } } + } - @Override - protected void onScrollChanged(int l, int t, int oldl, int oldt) { - super.onScrollChanged(l, t, oldl, oldt); - updateStickyHeaderPosition(); - } + @Override + protected void onScrollChanged(int l, int t, int oldl, int oldt) { + super.onScrollChanged(l, t, oldl, oldt); + updateStickyHeaderPosition(); + } - @Override - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - public WindowInsets onApplyWindowInsets(WindowInsets insets) { - if (getFitsSystemWindows()) { - mStatusBarInset = insets.getSystemWindowInsetTop(); - insets = insets.replaceSystemWindowInsets( - insets.getSystemWindowInsetLeft(), - 0, /* top */ - insets.getSystemWindowInsetRight(), - insets.getSystemWindowInsetBottom() - ); - } - return insets; + @Override + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public WindowInsets onApplyWindowInsets(WindowInsets insets) { + if (getFitsSystemWindows()) { + statusBarInset = insets.getSystemWindowInsetTop(); + insets = + insets.replaceSystemWindowInsets( + insets.getSystemWindowInsetLeft(), + 0, /* top */ + insets.getSystemWindowInsetRight(), + insets.getSystemWindowInsetBottom()); } + return insets; + } } diff --git a/library/main/src/com/android/setupwizardlib/view/TouchableMovementMethod.java b/library/main/src/com/android/setupwizardlib/view/TouchableMovementMethod.java index 10e91f4..526883c 100644 --- a/library/main/src/com/android/setupwizardlib/view/TouchableMovementMethod.java +++ b/library/main/src/com/android/setupwizardlib/view/TouchableMovementMethod.java @@ -24,60 +24,56 @@ import android.view.MotionEvent; import android.widget.TextView; /** - * A movement method that tracks the last result of whether touch events are handled. This is - * used to patch the return value of {@link TextView#onTouchEvent} so that it consumes the touch - * events only when the movement method says the event is consumed. + * A movement method that tracks the last result of whether touch events are handled. This is used + * to patch the return value of {@link TextView#onTouchEvent} so that it consumes the touch events + * only when the movement method says the event is consumed. */ public interface TouchableMovementMethod { - /** - * @return The last touch event received in {@link MovementMethod#onTouchEvent} - */ - MotionEvent getLastTouchEvent(); + /** @return The last touch event received in {@link MovementMethod#onTouchEvent} */ + MotionEvent getLastTouchEvent(); - /** - * @return The return value of the last {@link MovementMethod#onTouchEvent}, or whether the - * last touch event should be considered handled by the text view - */ - boolean isLastTouchEventHandled(); + /** + * @return The return value of the last {@link MovementMethod#onTouchEvent}, or whether the last + * touch event should be considered handled by the text view + */ + boolean isLastTouchEventHandled(); - /** - * An extension of LinkMovementMethod that tracks whether the event is handled when it is - * touched. - */ - class TouchableLinkMovementMethod extends LinkMovementMethod - implements TouchableMovementMethod { + /** + * An extension of LinkMovementMethod that tracks whether the event is handled when it is touched. + */ + class TouchableLinkMovementMethod extends LinkMovementMethod implements TouchableMovementMethod { - public static TouchableLinkMovementMethod getInstance() { - return new TouchableLinkMovementMethod(); - } + public static TouchableLinkMovementMethod getInstance() { + return new TouchableLinkMovementMethod(); + } - boolean mLastEventResult = false; - MotionEvent mLastEvent; + boolean lastEventResult = false; + MotionEvent lastEvent; - @Override - public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { - mLastEvent = event; - boolean result = super.onTouchEvent(widget, buffer, event); - if (event.getAction() == MotionEvent.ACTION_DOWN) { - // Unfortunately, LinkMovementMethod extends ScrollMovementMethod, and it always - // consume the down event. So here we use the selection instead as a hint of whether - // the down event landed on a link. - mLastEventResult = Selection.getSelectionStart(buffer) != -1; - } else { - mLastEventResult = result; - } - return result; - } + @Override + public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { + lastEvent = event; + boolean result = super.onTouchEvent(widget, buffer, event); + if (event.getAction() == MotionEvent.ACTION_DOWN) { + // Unfortunately, LinkMovementMethod extends ScrollMovementMethod, and it always + // consume the down event. So here we use the selection instead as a hint of whether + // the down event landed on a link. + lastEventResult = Selection.getSelectionStart(buffer) != -1; + } else { + lastEventResult = result; + } + return result; + } - @Override - public MotionEvent getLastTouchEvent() { - return mLastEvent; - } + @Override + public MotionEvent getLastTouchEvent() { + return lastEvent; + } - @Override - public boolean isLastTouchEventHandled() { - return mLastEventResult; - } + @Override + public boolean isLastTouchEventHandled() { + return lastEventResult; } + } } |