text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.os.Build; import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.annotation.StyleRes; import androidx.recyclerview.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; // This does not support view type, bind payload, getAdapterPosition(), etc. public class AdapterLinearLayout extends LinearLayout { protected RecyclerView.Adapter mAdapter; private final RecyclerView.AdapterDataObserver mObserver = new RecyclerView.AdapterDataObserver() { @Override public void onChanged() { onDataSetChanged(); } @Override public void onItemRangeChanged(int positionStart, int itemCount) { AdapterLinearLayout.this.onItemRangeChanged(positionStart, itemCount); } @Override public void onItemRangeInserted(int positionStart, int itemCount) { AdapterLinearLayout.this.onItemRangeInserted(positionStart, itemCount); } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { AdapterLinearLayout.this.onItemRangeRemoved(positionStart, itemCount); } @Override public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { AdapterLinearLayout.this.onItemRangeMoved(fromPosition, toPosition, itemCount); } }; public AdapterLinearLayout(@NonNull Context context) { super(context); } public AdapterLinearLayout(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public AdapterLinearLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public AdapterLinearLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public RecyclerView.Adapter getAdapter() { return mAdapter; } public void setAdapter(@Nullable RecyclerView.Adapter adapter) { if (mAdapter != null) { mAdapter.unregisterAdapterDataObserver(mObserver); } mAdapter = adapter; if (mAdapter != null) { adapter.registerAdapterDataObserver(mObserver); } onDataSetChanged(); } protected void onDataSetChanged() { removeAllViews(); if (mAdapter == null) { return; } for (int position = 0, count = mAdapter.getItemCount(); position < count; ++position) { addItemView(position); } } protected void onItemRangeChanged(int positionStart, int itemCount) { for (int position = positionStart, positionEnd = positionStart + itemCount; position < positionEnd; ++position) { updateItemView(position); } } protected void onItemRangeInserted(int positionStart, int itemCount) { for (int position = positionStart, positionEnd = positionStart + itemCount; position < positionEnd; ++position) { addItemView(position); } } protected void onItemRangeRemoved(int positionStart, int itemCount) { for (int i = 0; i < itemCount; ++i) { removeViewAt(positionStart); } } protected void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { View[] itemViews = new View[itemCount]; for (int i = 0; i < itemCount; ++i) { itemViews[i] = getChildAt(fromPosition); removeViewAt(fromPosition); } for (int i = 0, position = toPosition; i < itemCount; ++i, ++position) { addView(itemViews[i], position); } } private void addItemView(int position) { int viewType = mAdapter.getItemViewType(position); RecyclerView.ViewHolder holder = mAdapter.createViewHolder(this, viewType); //noinspection unchecked mAdapter.bindViewHolder(holder, position); View itemView = holder.itemView; itemView.setTag(holder); addView(itemView, position); } private void updateItemView(int position) { View itemView = getChildAt(position); RecyclerView.ViewHolder holder = (RecyclerView.ViewHolder) itemView.getTag(); //noinspection unchecked mAdapter.bindViewHolder(holder, position); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/AdapterLinearLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
909
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.util.AttributeSet; /** * @see MaxDimensionHelper * @see DispatchInsetsFrameLayout */ public class MaxDimensionDispatchInsetsFrameLayout extends DispatchInsetsFrameLayout { private MaxDimensionHelper mMaxDimensionHelper = new MaxDimensionHelper((widthSpec, heightSpec) -> MaxDimensionDispatchInsetsFrameLayout.super.onMeasure(widthSpec, heightSpec)); public MaxDimensionDispatchInsetsFrameLayout(Context context) { super(context); init(null, 0, 0); } public MaxDimensionDispatchInsetsFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0, 0); } public MaxDimensionDispatchInsetsFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr, 0); } public MaxDimensionDispatchInsetsFrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(attrs, defStyleAttr, defStyleRes); } private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) { mMaxDimensionHelper.init(getContext(), attrs, defStyleAttr, defStyleRes); } @Override protected void onMeasure(int widthSpec, int heightSpec) { mMaxDimensionHelper.onMeasure(widthSpec, heightSpec); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/MaxDimensionDispatchInsetsFrameLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
309
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import androidx.annotation.RequiresApi; import androidx.appcompat.widget.TintTypedArray; import android.util.AttributeSet; import android.widget.FrameLayout; import android.widget.ImageView; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.ImageUtils; import me.zhanghai.android.douya.util.ViewUtils; public class ImageLayout extends FrameLayout { public static final int FILL_ORIENTATION_HORIZONTAL = 0; public static final int FILL_ORIENTATION_VERTICAL = 1; @BindView(R.id.imagelayout_image) RatioImageView mImageView; @BindView(R.id.imagelayout_gif) ImageView mGifImage; public ImageLayout(Context context) { super(context); init(null, 0, 0); } public ImageLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0, 0); } public ImageLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr, 0); } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public ImageLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(attrs, defStyleAttr, defStyleRes); } @SuppressLint("RestrictedApi") private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) { setClickable(true); setFocusable(true); onInflateChildren(); ButterKnife.bind(this); TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs, R.styleable.ImageLayout, defStyleAttr, defStyleRes); int fillOrientation = a.getInt(R.styleable.ImageLayout_fillOrientation, FILL_ORIENTATION_HORIZONTAL); a.recycle(); LayoutParams layoutParams = (LayoutParams) mImageView.getLayoutParams(); layoutParams.width = fillOrientation == FILL_ORIENTATION_HORIZONTAL ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT; layoutParams.height = fillOrientation == FILL_ORIENTATION_HORIZONTAL ? LayoutParams.WRAP_CONTENT : LayoutParams.MATCH_PARENT; mImageView.setLayoutParams(layoutParams); } protected void onInflateChildren() { ViewUtils.inflateInto(R.layout.image_layout, this); } public void loadImage(SizedImageItem image) { ImageUtils.loadImageWithRatio(mImageView, image); ViewUtils.setVisibleOrGone(mGifImage, image.isAnimated()); } public void releaseImage() { mImageView.setImageDrawable(null); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/ImageLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
562
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import androidx.annotation.NonNull; import me.zhanghai.android.douya.util.MathUtils; public class RotateDrawableCompat extends DrawableWrapperCompat { private static final int MAX_LEVEL = 10000; private RotateState mState; public RotateDrawableCompat(Drawable drawable) { super(drawable); } @Override public void draw(@NonNull Canvas canvas) { Drawable drawable = getDrawable(); if (drawable == null) { return; } Rect bounds = drawable.getBounds(); int width = bounds.right - bounds.left; int height = bounds.bottom - bounds.top; float pivotX = mState.mIsPivotXRelative ? (width * mState.mPivotX) : mState.mPivotX; float pivotY = mState.mIsPivotYRelative ? (height * mState.mPivotY) : mState.mPivotY; int saveCount = canvas.save(); canvas.rotate(mState.mCurrentDegrees, bounds.left + pivotX, bounds.top + pivotY); drawable.draw(canvas); canvas.restoreToCount(saveCount); } /** * Sets the start angle for rotation. * * @param fromDegrees starting angle in degrees * @see #getFromDegrees() */ public void setFromDegrees(float fromDegrees) { if (mState.mFromDegrees == fromDegrees) { return; } mState.mFromDegrees = fromDegrees; invalidateSelf(); } /** * @return starting angle for rotation in degrees * @see #setFromDegrees(float) */ public float getFromDegrees() { return mState.mFromDegrees; } /** * Sets the end angle for rotation. * * @param toDegrees ending angle in degrees * @see #getToDegrees() */ public void setToDegrees(float toDegrees) { if (mState.mToDegrees == toDegrees) { return; } mState.mToDegrees = toDegrees; invalidateSelf(); } /** * @return ending angle for rotation in degrees * @see #setToDegrees(float) */ public float getToDegrees() { return mState.mToDegrees; } public void setDegrees(float degrees) { mState.mFromDegrees = mState.mToDegrees = mState.mCurrentDegrees = degrees; } /** * Sets the X position around which the drawable is rotated. * <p> * If the X pivot is relative (as specified by * {@link #setPivotXRelative(boolean)}), then the position represents a * fraction of the drawable width. Otherwise, the position represents an * absolute value in pixels. * * @param pivotX X position around which to rotate * @see #setPivotXRelative(boolean) */ public void setPivotX(float pivotX) { if (mState.mPivotX == pivotX) { return; } mState.mPivotX = pivotX; invalidateSelf(); } /** * @return X position around which to rotate * @see #setPivotX(float) */ public float getPivotX() { return mState.mPivotX; } /** * Sets whether the X pivot value represents a fraction of the drawable * width or an absolute value in pixels. * * @param relative true if the X pivot represents a fraction of the drawable * width, or false if it represents an absolute value in pixels * @see #isPivotXRelative() */ public void setPivotXRelative(boolean relative) { if (mState.mIsPivotXRelative == relative) { return; } mState.mIsPivotXRelative = relative; invalidateSelf(); } /** * @return true if the X pivot represents a fraction of the drawable width, * or false if it represents an absolute value in pixels * @see #setPivotXRelative(boolean) */ public boolean isPivotXRelative() { return mState.mIsPivotXRelative; } /** * Sets the Y position around which the drawable is rotated. * <p> * If the Y pivot is relative (as specified by * {@link #setPivotYRelative(boolean)}), then the position represents a * fraction of the drawable height. Otherwise, the position represents an * absolute value in pixels. * * @param pivotY Y position around which to rotate * @see #getPivotY() */ public void setPivotY(float pivotY) { if (mState.mPivotY == pivotY) { return; } mState.mPivotY = pivotY; invalidateSelf(); } /** * @return Y position around which to rotate * @see #setPivotY(float) */ public float getPivotY() { return mState.mPivotY; } /** * Sets whether the Y pivot value represents a fraction of the drawable * height or an absolute value in pixels. * * @param relative True if the Y pivot represents a fraction of the drawable * height, or false if it represents an absolute value in pixels * @see #isPivotYRelative() */ public void setPivotYRelative(boolean relative) { if (mState.mIsPivotYRelative == relative) { return; } mState.mIsPivotYRelative = relative; invalidateSelf(); } /** * @return true if the Y pivot represents a fraction of the drawable height, * or false if it represents an absolute value in pixels * @see #setPivotYRelative(boolean) */ public boolean isPivotYRelative() { return mState.mIsPivotYRelative; } @Override protected boolean onLevelChange(int level) { super.onLevelChange(level); float value = level / (float) MAX_LEVEL; mState.mCurrentDegrees = MathUtils.lerp(mState.mFromDegrees, mState.mToDegrees, value); invalidateSelf(); return true; } @Override protected RotateState mutateConstantState() { mState = new RotateState(mState, null); return mState; } private static final class RotateState extends DrawableWrapperState { boolean mIsPivotXRelative = true; float mPivotX = 0.5f; boolean mIsPivotYRelative = true; float mPivotY = 0.5f; float mFromDegrees = 0.0f; float mToDegrees = 360.0f; float mCurrentDegrees = 0.0f; RotateState(RotateState orig, Resources res) { super(orig, res); if (orig != null) { mIsPivotXRelative = orig.mIsPivotXRelative; mPivotX = orig.mPivotX; mIsPivotYRelative = orig.mIsPivotYRelative; mPivotY = orig.mPivotY; mFromDegrees = orig.mFromDegrees; mToDegrees = orig.mToDegrees; mCurrentDegrees = orig.mCurrentDegrees; } } @NonNull @Override public Drawable newDrawable(Resources res) { return new RotateDrawableCompat(this, res); } } private RotateDrawableCompat(RotateState state, Resources res) { super(state, res); mState = state; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/RotateDrawableCompat.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,703
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.graphics.Canvas; import android.graphics.Paint; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.text.style.ReplacementSpan; public class SpaceSpan extends ReplacementSpan { private float mWidthEm; public SpaceSpan(float widthEm) { mWidthEm = widthEm; } @Override public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) { return Math.round(mWidthEm * paint.getTextSize()); } @Override public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {} } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/SpaceSpan.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
169
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import android.util.SparseIntArray; import android.view.ViewGroup; import java.util.List; import me.zhanghai.android.douya.util.LogUtils; public class MergeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { @NonNull private final RecyclerView.Adapter[] mAdapters; @NonNull private final SparseIntArray mItemViewTypeToAdapterIndexMap = new SparseIntArray(); public MergeAdapter(@NonNull RecyclerView.Adapter... adapters) { mAdapters = adapters; for (RecyclerView.Adapter adapter : mAdapters) { adapter.registerAdapterDataObserver(new AdapterDataObserver(adapter)); } boolean hasStableIds = true; for (RecyclerView.Adapter adapter : mAdapters) { if (!adapter.hasStableIds()) { hasStableIds = false; LogUtils.w("not all adapters have stable ids: " + adapter); } } super.setHasStableIds(hasStableIds); } @NonNull public RecyclerView.Adapter[] getAdapters() { return mAdapters; } @Override public void setHasStableIds(boolean hasStableIds) { throw new UnsupportedOperationException("cannot set hasStableIds on MergeAdapter"); } @Override public int getItemCount() { int count = 0; for (RecyclerView.Adapter adapter : mAdapters) { count += adapter.getItemCount(); } return count; } @Override public long getItemId(int position) { int adapterIndex = 0; for (RecyclerView.Adapter adapter : mAdapters) { int count = adapter.getItemCount(); if (position < count) { return 31 * adapterIndex + adapter.getItemId(position); } position -= count; ++adapterIndex; } throw new IllegalStateException("Unknown position: " + position); } @Override public int getItemViewType(int position) { int adapterIndex = 0; for (RecyclerView.Adapter adapter : mAdapters) { int count = adapter.getItemCount(); if (position < count) { int itemViewType = (adapterIndex << 16) + adapter.getItemViewType(position); mItemViewTypeToAdapterIndexMap.put(itemViewType, adapterIndex); return itemViewType; } position -= count; ++adapterIndex; } throw new IllegalStateException("Unknown position: " + position); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { int adapterIndex = getAdapterIndexForViewType(viewType); return mAdapters[adapterIndex].onCreateViewHolder(parent, viewType - (adapterIndex << 16)); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { for (RecyclerView.Adapter adapter : mAdapters) { int count = adapter.getItemCount(); if (position < count) { //noinspection unchecked adapter.onBindViewHolder(holder, position); return; } position -= count; } throw new IllegalStateException("Unknown position: " + position); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads) { for (RecyclerView.Adapter adapter : mAdapters) { int count = adapter.getItemCount(); if (position < count) { //noinspection unchecked adapter.onBindViewHolder(holder, position, payloads); return; } position -= count; } throw new IllegalStateException("Unknown position: " + position); } @Override public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) { int adapterIndex = getAdapterIndexForViewType(holder.getItemViewType()); //noinspection unchecked mAdapters[adapterIndex].onViewRecycled(holder); } @Override public boolean onFailedToRecycleView(@NonNull RecyclerView.ViewHolder holder) { int position = holder.getAdapterPosition(); for (RecyclerView.Adapter adapter : mAdapters) { int count = adapter.getItemCount(); if (position < count) { //noinspection unchecked return adapter.onFailedToRecycleView(holder); } position -= count; } throw new IllegalStateException("Unknown position: " + position); } @Override public void onViewAttachedToWindow(@NonNull RecyclerView.ViewHolder holder) { int position = holder.getAdapterPosition(); for (RecyclerView.Adapter adapter : mAdapters) { int count = adapter.getItemCount(); if (position < count) { //noinspection unchecked adapter.onViewAttachedToWindow(holder); return; } position -= count; } throw new IllegalStateException("Unknown position: " + position); } @Override public void onViewDetachedFromWindow(@NonNull RecyclerView.ViewHolder holder) { int position = holder.getAdapterPosition(); for (RecyclerView.Adapter adapter : mAdapters) { int count = adapter.getItemCount(); if (position < count) { //noinspection unchecked adapter.onViewDetachedFromWindow(holder); return; } position -= count; } throw new IllegalStateException("Unknown position: " + position); } @Override public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) { for (RecyclerView.Adapter adapter : mAdapters) { adapter.onAttachedToRecyclerView(recyclerView); } } @Override public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) { for (RecyclerView.Adapter adapter : mAdapters) { adapter.onDetachedFromRecyclerView(recyclerView); } } private int getAdapterIndexForViewType(int viewType) { int mapIndex = mItemViewTypeToAdapterIndexMap.indexOfKey(viewType); if (mapIndex < 0) { throw new IllegalStateException("Unknown viewType: " + viewType); } return mItemViewTypeToAdapterIndexMap.valueAt(mapIndex); } private class AdapterDataObserver extends RecyclerView.AdapterDataObserver { private final RecyclerView.Adapter mAdapter; public AdapterDataObserver(@NonNull RecyclerView.Adapter adapter) { mAdapter = adapter; } @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onItemRangeChanged(int positionStart, int itemCount) { notifyItemRangeChanged(getItemPosition(positionStart), itemCount); } @Override public void onItemRangeChanged(int positionStart, int itemCount, Object payload) { notifyItemRangeChanged(getItemPosition(positionStart), itemCount, payload); } @Override public void onItemRangeInserted(int positionStart, int itemCount) { notifyItemRangeInserted(getItemPosition(positionStart), itemCount); } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { notifyItemRangeRemoved(getItemPosition(positionStart), itemCount); } @Override public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { if (itemCount != 1) { throw new IllegalArgumentException("Moving more than 1 item is not supported yet"); } notifyItemMoved(getItemPosition(fromPosition), getItemPosition(toPosition)); } private int getItemPosition(int position) { for (RecyclerView.Adapter adapter : mAdapters) { if (adapter == mAdapter) { break; } else { position += adapter.getItemCount(); } } return position; } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/MergeAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,596
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.ViewUtils; public class HorizontalImageAdapter extends ClickableSimpleAdapter<SizedImageItem, HorizontalImageAdapter.ViewHolder> { public HorizontalImageAdapter() { setHasStableIds(true); } @Override public long getItemId(int position) { // Deliberately using plain hash code to identify only this instance. return getItem(position).hashCode(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(ViewUtils.inflate(R.layout.horizontal_image_item, parent)); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { holder.imageLayout.loadImage(getItem(position)); } static class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.image) public ImageLayout imageLayout; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/HorizontalImageAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
251
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import androidx.appcompat.widget.AppCompatTextView; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.widget.EditText; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.ViewUtils; public class CounterTextView extends AppCompatTextView { private EditText mEditText; private int mMaxLength; public CounterTextView(Context context) { super(context); } public CounterTextView(Context context, AttributeSet attrs) { super(context, attrs); } public CounterTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setEditText(EditText editText, int maxLength) { mEditText = editText; mMaxLength = maxLength; mEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { updateText(); } }); updateText(); } private void updateText() { int length = mEditText.length(); boolean visible = length > mMaxLength / 2; ViewUtils.fadeToVisibility(this, visible, false); if (visible) { setText(getContext().getString(R.string.counter_format, length, mMaxLength)); int textColorAttrRes = length <= mMaxLength ? android.R.attr.textColorSecondary : R.attr.colorError; setTextColor(ViewUtils.getColorStateListFromAttrRes(textColorAttrRes, getContext())); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/CounterTextView.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
371
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.app.Activity; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import java.util.List; import androidx.swiperefreshlayout.widget.FriendlySwipeRefreshLayout; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.content.MoreListResourceFragment; import me.zhanghai.android.douya.network.api.ApiError; import me.zhanghai.android.douya.util.LogUtils; import me.zhanghai.android.douya.util.ToastUtils; import me.zhanghai.android.douya.util.ViewUtils; public abstract class BaseListFragment<T> extends Fragment { @BindView(R.id.swipe_refresh) protected FriendlySwipeRefreshLayout mSwipeRefreshLayout; @BindView(R.id.list) protected RecyclerView mList; @BindView(R.id.progress) protected ProgressBar mProgress; protected SimpleAdapter<T, ?> mItemAdapter; protected LoadMoreAdapter mAdapter; protected MoreListResourceFragment<?, List<T>> mResource; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.base_list_fragment, container, false); } @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mResource = onAttachResource(); mSwipeRefreshLayout.setOnRefreshListener(this::onSwipeRefresh); // TODO: OK? //mList.setHasFixedSize(true); mList.setItemAnimator(new NoChangeAnimationItemAnimator()); mList.setLayoutManager(onCreateLayoutManager()); mItemAdapter = onCreateAdapter(); if (mResource.has()) { mItemAdapter.replace(mResource.get()); } mAdapter = new LoadMoreAdapter(mItemAdapter); mList.setAdapter(mAdapter); onAttachScrollListener(); updateRefreshing(); } protected RecyclerView.LayoutManager onCreateLayoutManager() { return new LinearLayoutManager(getActivity()); } abstract protected SimpleAdapter<T, ?> onCreateAdapter(); protected void onAttachScrollListener() { mList.addOnScrollListener(new OnVerticalScrollListener() { @Override public void onScrolledToBottom() { mResource.load(true); } }); } @Override public void onDestroy() { super.onDestroy(); mResource.detach(); } protected abstract MoreListResourceFragment<?, List<T>> onAttachResource(); protected void onLoadListStarted() { updateRefreshing(); } protected void onLoadListFinished() { updateRefreshing(); } protected void onLoadListError(ApiError error) { LogUtils.e(error.toString()); Activity activity = getActivity(); ToastUtils.show(ApiError.getErrorString(error, activity), activity); } protected void onListChanged(List<T> newList) { mItemAdapter.replace(newList); //noinspection unchecked onListUpdated(mResource.get()); } protected void onListAppended(List<T> appendedList) { mItemAdapter.addAll(appendedList); //noinspection unchecked onListUpdated(mResource.get()); } protected void onItemChanged(int position, T newItem) { mItemAdapter.set(position, newItem); //noinspection unchecked onListUpdated(mResource.get()); } protected void onItemInserted(int position, T insertedItem) { mItemAdapter.add(position, insertedItem); //noinspection unchecked onListUpdated(mResource.get()); } protected void onItemRemoved(int position) { mItemAdapter.remove(position); //noinspection unchecked onListUpdated(mResource.get()); } protected void onListUpdated(List<T> list) {} protected void onItemWriteFinished(int position) { mItemAdapter.notifyItemChanged(position); } protected void onItemWriteStarted(int position) { mItemAdapter.notifyItemChanged(position); } private void updateRefreshing() { boolean loading = mResource.isLoading(); boolean empty = mResource.isEmpty(); boolean loadingMore = mResource.isLoadingMore(); mSwipeRefreshLayout.setRefreshing(loading && (mSwipeRefreshLayout.isRefreshing() || !empty) && !loadingMore); ViewUtils.setVisibleOrGone(mProgress, loading && empty); mAdapter.setLoading(loading && !empty && loadingMore); } protected void onSwipeRefresh() { mResource.load(false); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/BaseListFragment.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
993
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.LinearLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; public class CheckableLinearLayout extends LinearLayout implements Checkable { private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked }; private boolean mChecked; public CheckableLinearLayout(@NonNull Context context) { super(context); } public CheckableLinearLayout(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public CheckableLinearLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public CheckableLinearLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public void toggle() { setChecked(!mChecked); } public boolean isChecked() { return mChecked; } public void setChecked(boolean checked) { if (mChecked != checked) { mChecked = checked; refreshDrawableState(); } } @Override protected int[] onCreateDrawableState(int extraSpace) { int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/CheckableLinearLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
341
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import androidx.cardview.widget.CardView; import androidx.appcompat.widget.TintTypedArray; import android.util.AttributeSet; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.ViewUtils; /** * A friendly card view that has consistent padding across API levels. */ public class FriendlyCardView extends CardView { public FriendlyCardView(Context context) { super(context); init(null, 0); } public FriendlyCardView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public FriendlyCardView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @SuppressLint("RestrictedApi") private void init(AttributeSet attrs, int defStyleAttr) { TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs, R.styleable.CardView, defStyleAttr, R.style.CardView); setMaxCardElevation(a.getDimension(R.styleable.CardView_cardMaxElevation, getCardElevation())); a.recycle(); setUseCompatPadding(true); setPreventCornerOverlap(false); // User should never click through a card. setClickable(true); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); // Fix off-by-one-pixel negative margin. Resources resources = getResources(); int cardShadowHorizontalMargin = resources.getDimensionPixelOffset( R.dimen.card_shadow_horizontal_margin); if (ViewUtils.getMarginLeft(this) == cardShadowHorizontalMargin) { ViewUtils.setMarginLeft(this, getContentPaddingLeft() - getPaddingLeft()); } if (ViewUtils.getMarginRight(this) == cardShadowHorizontalMargin) { ViewUtils.setMarginRight(this, getContentPaddingRight() - getPaddingRight()); } int cardShadowVerticalMargin = resources.getDimensionPixelOffset( R.dimen.card_shadow_vertical_margin); if (ViewUtils.getMarginTop(this) == cardShadowVerticalMargin) { ViewUtils.setMarginTop(this, getContentPaddingTop() - getPaddingTop()); } if (ViewUtils.getMarginBottom(this) == cardShadowVerticalMargin) { ViewUtils.setMarginBottom(this, getContentPaddingBottom() - getPaddingBottom()); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/FriendlyCardView.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
523
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.widget.FrameLayout; public class RatioFrameLayout extends FrameLayout { private float mRatio; public RatioFrameLayout(Context context) { super(context); } public RatioFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } public RatioFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public RatioFrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public float getRatio() { return mRatio; } public void setRatio(float ratio) { if (mRatio != ratio) { mRatio = ratio; requestLayout(); invalidate(); } } public void setRatio(float width, float height) { setRatio(width / height); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mRatio > 0) { if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) { int height = MeasureSpec.getSize(heightMeasureSpec); int width = Math.round(mRatio * height); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { width = Math.max(width, getMinimumWidth()); } widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); } else { int width = MeasureSpec.getSize(widthMeasureSpec); int height = Math.round(width / mRatio); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { height = Math.max(height, getMinimumHeight()); } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/RatioFrameLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
438
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.net.Uri; import android.os.Build; import androidx.annotation.RequiresApi; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.ImageUtils; import me.zhanghai.android.douya.util.UriUtils; import me.zhanghai.android.douya.util.ViewUtils; public class UploadImageLayout extends FrameLayout { @BindView(R.id.uploadimagelayout_image) RatioImageView mImageView; @BindView(R.id.uploadimagelayout_gif) ImageView mGifImage; @BindView(R.id.uploadimagelayout_remove) ImageButton mRemoveButton; private boolean mInImageList; public UploadImageLayout(Context context) { super(context); init(); } public UploadImageLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public UploadImageLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public UploadImageLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { setClickable(true); setFocusable(true); ViewUtils.inflateInto(R.layout.upload_image_layout, this); ButterKnife.bind(this); setInImageListInt(false); } public void setInImageList(boolean inImageList) { if (mInImageList != inImageList) { setInImageListInt(inImageList); } } private void setInImageListInt(boolean inImageList) { mInImageList = inImageList; mImageView.setRatio(mInImageList ? 1 : (6f / 5f)); LayoutParams layoutParams = (LayoutParams) mImageView.getLayoutParams(); layoutParams.width = mInImageList ? LayoutParams.WRAP_CONTENT : LayoutParams.MATCH_PARENT; layoutParams.height = mInImageList ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT; mImageView.setLayoutParams(layoutParams); } public void loadImage(Uri imageUri) { ImageUtils.loadImage(mImageView, imageUri); String type = UriUtils.getType(imageUri, getContext()); boolean isGif = TextUtils.equals(type, "image/gif"); ViewUtils.setVisibleOrGone(mGifImage, isGif); } public void releaseImage() { mImageView.setImageDrawable(null); } public void setRemoveButtonOnClickListener(View.OnClickListener listener) { mRemoveButton.setOnClickListener(listener); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/UploadImageLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
611
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.app.Activity; public interface FragmentFinishable { void finishFromFragment(); void finishAfterTransitionFromFragment(); static void finish(Activity activity) { ((FragmentFinishable) activity).finishFromFragment(); } static void finishAfterTransition(Activity activity) { ((FragmentFinishable) activity).finishAfterTransitionFromFragment(); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/FragmentFinishable.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
93
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import androidx.drawerlayout.widget.DrawerLayout; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.WindowInsets; import me.zhanghai.android.douya.util.ViewUtils; /** * Layouts in fullscreen, and {@code android:fitsSystemWindows="true"} will be ignored. * * @see DispatchInsetsHelper */ public class DispatchInsetsDrawerLayout extends DrawerLayout { private DispatchInsetsHelper mInsetsHelper = new DispatchInsetsHelper( new DispatchInsetsHelper.Delegate() { @Override public int getGravityFromLayoutParams(ViewGroup.LayoutParams layoutParams) { return ((LayoutParams) layoutParams).gravity; } @Override public ViewGroup getOwner() { return DispatchInsetsDrawerLayout.this; } @Override public void superAddView(View child, int index, ViewGroup.LayoutParams params) { DispatchInsetsDrawerLayout.super.addView(child, index, params); } @Override public boolean superAddViewInLayout(View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout) { return DispatchInsetsDrawerLayout.super.addViewInLayout(child, index, params, preventRequestLayout); } }); public DispatchInsetsDrawerLayout(Context context) { super(context); init(); } public DispatchInsetsDrawerLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DispatchInsetsDrawerLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { setFitsSystemWindows(false); ViewUtils.setLayoutFullscreen(this); } @Override public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { return mInsetsHelper.dispatchApplyWindowInsets(insets); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { mInsetsHelper.addView(child, index, params); } @Override protected boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout) { return mInsetsHelper.addViewInLayout(child, index, params, preventRequestLayout); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/DispatchInsetsDrawerLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
478
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import androidx.appcompat.widget.TintTypedArray; import android.util.AttributeSet; import android.view.Gravity; import android.widget.ImageView; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.ViewUtils; public class CardIconButton extends GetOnLongClickListenerLinearLayout { @BindView(R.id.cardiconbutton_image) ImageView mImage; @BindView(R.id.cardiconbutton_text) TextView mText; public CardIconButton(Context context) { super(context); init(null, 0, 0); } public CardIconButton(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0, 0); } public CardIconButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr, 0); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public CardIconButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(attrs, defStyleAttr, defStyleRes); } @SuppressLint("RestrictedApi") private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) { setClickable(true); setFocusable(true); setGravity(Gravity.CENTER_VERTICAL); setOrientation(HORIZONTAL); ViewUtils.inflateInto(R.layout.card_icon_button, this); ButterKnife.bind(this); TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs, R.styleable.CardIconButton, defStyleAttr, defStyleRes); Drawable src = a.getDrawable(R.styleable.CardIconButton_android_src); if (src != null) { mImage.setImageDrawable(src); } CharSequence text = a.getText(R.styleable.CardIconButton_android_text); setText(text); a.recycle(); } public ImageView getImageView() { return mImage; } public TextView getTextView() { return mText; } public void setIcon(Drawable icon) { mImage.setImageDrawable(icon); } public void setText(CharSequence text) { mText.setText(text); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/CardIconButton.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
499
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import androidx.core.view.ViewCompat; import androidx.appcompat.content.res.AppCompatResources; import android.text.TextUtils; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ImageView; import android.widget.TextView; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.TooltipUtils; import me.zhanghai.android.douya.util.ViewUtils; public class ActionItemBadge { public static void setup(MenuItem menuItem, Drawable icon, int count, Activity activity) { View actionView = menuItem.getActionView(); actionView.setOnClickListener(view -> activity.onMenuItemSelected( Window.FEATURE_OPTIONS_PANEL, menuItem)); CharSequence title = menuItem.getTitle(); if (!TextUtils.isEmpty(title)) { actionView.setContentDescription(title); TooltipUtils.setup(actionView); } ImageView iconImage = actionView.findViewById(R.id.icon); iconImage.setImageDrawable(icon); TextView badgeText = actionView.findViewById(R.id.badge); Context themedContext = badgeText.getContext(); ViewCompat.setBackground(badgeText, new BadgeDrawable(themedContext)); badgeText.setTextColor(ViewUtils.getColorFromAttrRes(R.attr.colorPrimary, 0, themedContext)); update(badgeText, count); } public static void setup(MenuItem menuItem, int iconResId, int count, Activity activity) { setup(menuItem, AppCompatResources.getDrawable(activity, iconResId), count, activity); } private static void update(TextView badgeText, int count) { boolean hasBadge = count > 0; // Don't set the badge count to 0 if we are fading away. if (hasBadge) { badgeText.setText(String.valueOf(count)); } // We are using android:animateLayoutChanges="true", so no need animating here. ViewUtils.setVisibleOrGone(badgeText, hasBadge); } public static void update(MenuItem menuItem, int count) { update(menuItem.getActionView().<TextView>findViewById(R.id.badge), count); } private static class BadgeDrawable extends GradientDrawable { public BadgeDrawable(Context context) { setColor(ViewUtils.getColorFromAttrRes(R.attr.colorControlNormal, 0, context)); } @Override public void setBounds(int left, int top, int right, int bottom) { super.setBounds(left, top, right, bottom); setCornerRadius(Math.min(right - left, bottom - top)); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/ActionItemBadge.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
556
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import androidx.annotation.NonNull; import androidx.core.graphics.drawable.DrawableCompat; import androidx.core.view.GravityCompat; import androidx.core.view.ViewCompat; import androidx.appcompat.widget.TintTypedArray; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; public class ForegroundHelper { private static final int[] STYLEABLE = { android.R.attr.foreground, android.R.attr.foregroundGravity }; private static final int STYLEABLE_ANDROID_FOREGROUND = 0; private static final int STYLEABLE_ANDROID_FOREGROUND_GRAVITY = 1; private Delegate mDelegate; private boolean mHasFrameworkForeground; private Drawable mForeground; private final Rect mSelfBounds = new Rect(); private final Rect mOverlayBounds = new Rect(); private int mForegroundGravity = Gravity.FILL; private boolean mForegroundBoundsChanged = false; public ForegroundHelper(Delegate delegate) { mDelegate = delegate; } @SuppressLint("RestrictedApi") public void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // @see View#View(android.content.Context, android.util.AttributeSet, int, int) mHasFrameworkForeground = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.M) || mDelegate.getOwner() instanceof FrameLayout; if (mHasFrameworkForeground) { return; } TintTypedArray a = TintTypedArray.obtainStyledAttributes(context, attrs, STYLEABLE, defStyleAttr, defStyleRes); mForegroundGravity = a.getInt(STYLEABLE_ANDROID_FOREGROUND_GRAVITY, mForegroundGravity); Drawable foreground = a.getDrawable(STYLEABLE_ANDROID_FOREGROUND); if (foreground != null) { setForeground(foreground); } a.recycle(); } public int getForegroundGravity() { if (mHasFrameworkForeground) { return mDelegate.superGetForegroundGravity(); } return mForegroundGravity; } public void setForegroundGravity(int foregroundGravity) { if (mHasFrameworkForeground) { mDelegate.superSetForegroundGravity(foregroundGravity); return; } if (mForegroundGravity != foregroundGravity) { if ((foregroundGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { foregroundGravity |= Gravity.START; } if ((foregroundGravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { foregroundGravity |= Gravity.TOP; } mForegroundGravity = foregroundGravity; mDelegate.getOwner().requestLayout(); } } public void setVisibility(int visibility) { mDelegate.superSetVisibility(visibility); if (mHasFrameworkForeground) { return; } if (mForeground != null) { mForeground.setVisible(visibility == View.VISIBLE, false); } } public boolean verifyDrawable(Drawable who) { if (mHasFrameworkForeground) { return mDelegate.superVerifyDrawable(who); } return mDelegate.superVerifyDrawable(who) || (who == mForeground); } public void jumpDrawablesToCurrentState() { mDelegate.superJumpDrawablesToCurrentState(); if (mHasFrameworkForeground) { return; } if (mForeground != null) { mForeground.jumpToCurrentState(); } } public void drawableStateChanged() { mDelegate.superDrawableStateChanged(); if (mHasFrameworkForeground) { return; } if (mForeground != null && mForeground.isStateful()) { mForeground.setState(mDelegate.getOwner().getDrawableState()); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public void drawableHotspotChanged(float x, float y) { mDelegate.superDrawableHotspotChanged(x, y); if (mHasFrameworkForeground) { return; } if (mForeground != null) { mForeground.setHotspot(x, y); } } public void setForeground(Drawable foreground) { if (mHasFrameworkForeground) { mDelegate.superSetForeground(foreground); return; } if (mForeground != foreground) { View owner = mDelegate.getOwner(); if (mForeground != null) { mForeground.setCallback(null); owner.unscheduleDrawable(mForeground); } mForeground = foreground; if (foreground != null) { owner.setWillNotDraw(false); foreground.setCallback(owner); DrawableCompat.setLayoutDirection(foreground, ViewCompat.getLayoutDirection(owner)); if (foreground.isStateful()) { foreground.setState(owner.getDrawableState()); } } else { owner.setWillNotDraw(true); } owner.requestLayout(); owner.invalidate(); } } public Drawable getForeground() { if (mHasFrameworkForeground) { return mDelegate.superGetForeground(); } return mForeground; } public void onLayout(boolean changed, int left, int top, int right, int bottom) { mDelegate.superOnLayout(changed, left, top, right, bottom); if (mHasFrameworkForeground) { return; } mForegroundBoundsChanged = true; } public void onSizeChanged(int w, int h, int oldw, int oldh) { mDelegate.superOnSizeChanged(w, h, oldw, oldh); if (mHasFrameworkForeground) { return; } mForegroundBoundsChanged = true; } public void draw(@NonNull Canvas canvas) { mDelegate.superDraw(canvas); if (mHasFrameworkForeground) { return; } if (mForeground != null) { final Drawable foreground = mForeground; if (mForegroundBoundsChanged) { View owner = mDelegate.getOwner(); mForegroundBoundsChanged = false; Rect selfBounds = mSelfBounds; Rect overlayBounds = mOverlayBounds; int w = owner.getRight() - owner.getLeft(); int h = owner.getBottom() - owner.getTop(); selfBounds.set(0, 0, w, h); int layoutDirection = ViewCompat.getLayoutDirection(owner); GravityCompat.apply(mForegroundGravity, foreground.getIntrinsicWidth(), foreground.getIntrinsicHeight(), selfBounds, overlayBounds, layoutDirection); foreground.setBounds(overlayBounds); } foreground.draw(canvas); } } public interface Delegate { View getOwner(); int superGetForegroundGravity(); void superSetForegroundGravity(int foregroundGravity); void superSetVisibility(int visibility); boolean superVerifyDrawable(Drawable who); void superJumpDrawablesToCurrentState(); void superDrawableStateChanged(); void superDrawableHotspotChanged(float x, float y); void superSetForeground(Drawable foreground); Drawable superGetForeground(); void superOnLayout(boolean changed, int left, int top, int right, int bottom); void superOnSizeChanged(int w, int h, int oldw, int oldh); void superDraw(@NonNull Canvas canvas); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/ForegroundHelper.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,560
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import androidx.recyclerview.widget.RecyclerView; public abstract class OnHorizontalScrollListener extends RecyclerView.OnScrollListener { @Override public final void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (!recyclerView.canScrollHorizontally(-1)) { onScrolledToLeft(); } else if (!recyclerView.canScrollHorizontally(1)) { onScrolledToRight(); } else if (dx < 0) { onScrolledLeft(); } else if (dx > 0) { onScrolledRight(); } } public void onScrolledLeft() {} public void onScrolledRight() {} public void onScrolledToLeft() {} public void onScrolledToRight() {} } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/OnHorizontalScrollListener.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
177
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; public interface FlexibleSpaceHeaderView { int getScroll(); int getScrollExtent(); void scrollTo(int scroll); } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/FlexibleSpaceHeaderView.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
43
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import androidx.interpolator.view.animation.FastOutLinearInInterpolator; import androidx.interpolator.view.animation.FastOutSlowInInterpolator; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import butterknife.BindInt; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.ViewUtils; /** * A {@link LinearLayout} that manages showing and hiding the AppBar and its shadow with support. */ public class AppBarWrapperLayout extends LinearLayout { @BindInt(android.R.integer.config_shortAnimTime) int mAnimationDuration; private View mAppbarView; private View mShadowCompatView; private boolean mShowing = true; private AnimatorSet mAnimator; public AppBarWrapperLayout(Context context) { super(context); init(); } public AppBarWrapperLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public AppBarWrapperLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public AppBarWrapperLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { setOrientation(VERTICAL); ButterKnife.bind(this); } @Override protected void onFinishInflate() { super.onFinishInflate(); ViewUtils.inflateInto(R.layout.appbar_shadow_compat, this); if (getChildCount() != 2) { throw new IllegalStateException("One and only one AppBar view should be wrapped " + "inside this layout"); } mAppbarView = getChildAt(0); mShadowCompatView = getChildAt(1); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.showing = mShowing; return savedState; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); if (!savedState.showing) { hideImmediately(); } } public boolean isShown() { return getTranslationY() == 0; } public boolean isHidden() { return getTranslationY() == getHideTranslationY(); } public boolean isShowing() { return mShowing; } public boolean isHiding() { return !mShowing; } public void hide() { if (!mShowing) { return; } mShowing = false; cancelAnimator(); mAnimator = new AnimatorSet() .setDuration(mAnimationDuration); mAnimator.setInterpolator(new FastOutLinearInInterpolator()); AnimatorSet.Builder builder = mAnimator.play(ObjectAnimator.ofFloat(this, TRANSLATION_Y, getTranslationY(), getHideTranslationY())); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { builder.before(ObjectAnimator.ofFloat(mShadowCompatView, ALPHA, mShadowCompatView.getAlpha(), 0)); } else { builder.before(ObjectAnimator.ofFloat(mAppbarView, TRANSLATION_Z, mAppbarView.getTranslationZ(), -mAppbarView.getElevation())); } startAnimator(); } public void hideImmediately() { if (!mShowing) { return; } float hideTranslationY = getHideTranslationY(); if (hideTranslationY != 0) { mShowing = false; setTranslationY(hideTranslationY); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { mShadowCompatView.setAlpha(0); } else { mAppbarView.setTranslationZ(-mAppbarView.getElevation()); } } else { ViewUtils.postOnPreDraw(this, new Runnable() { @Override public void run() { hideImmediately(); } }); } } private int getHideTranslationY() { return -(getBottom() - mShadowCompatView.getHeight()); } public void show() { if (mShowing) { return; } mShowing = true; cancelAnimator(); mAnimator = new AnimatorSet() .setDuration(mAnimationDuration); mAnimator.setInterpolator(new FastOutSlowInInterpolator()); AnimatorSet.Builder builder = mAnimator.play(ObjectAnimator.ofFloat(this, TRANSLATION_Y, getTranslationY(), 0)); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { builder.with(ObjectAnimator.ofFloat(mShadowCompatView, ALPHA, mShadowCompatView.getAlpha(), 1)); } else { builder.with(ObjectAnimator.ofFloat(mAppbarView, TRANSLATION_Z, mAppbarView.getTranslationZ(), 0)); } startAnimator(); } public void showImmediately() { if (mShowing) { return; } mShowing = true; setTranslationY(0); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { mShadowCompatView.setAlpha(1); } else { mAppbarView.setTranslationZ(0); } } private void startAnimator() { mAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationCancel(Animator animation) { mAnimator = null; } @Override public void onAnimationEnd(Animator animation) { mAnimator = null; } }); mAnimator.start(); } private void cancelAnimator() { if (mAnimator != null) { mAnimator.cancel(); mAnimator = null; } } private static class SavedState extends BaseSavedState { public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel source) { return new SavedState(source); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; public boolean showing; public SavedState(Parcel in) { super(in); showing = in.readByte() != 0; } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeByte(showing ? (byte) 1 : (byte) 0); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/AppBarWrapperLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,494
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; public interface ImageItem { String getLargeUrl(); String getMediumUrl(); String getSmallUrl(); boolean isAnimated(); } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/ImageItem.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
48
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.tabs.TabLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import java.util.ArrayList; import java.util.List; public class TabFragmentPagerAdapter extends FragmentPagerAdapter { @NonNull private final List<FragmentCreator> mFragmentCreatorList = new ArrayList<>(); @NonNull private final List<CharSequence> mTitleList = new ArrayList<>(); @Deprecated public TabFragmentPagerAdapter(@NonNull FragmentManager fragmentManager) { super(fragmentManager); } public TabFragmentPagerAdapter(@NonNull FragmentActivity activity) { //noinspection deprecation this(activity.getSupportFragmentManager()); } public TabFragmentPagerAdapter(@NonNull Fragment fragment) { //noinspection deprecation this(fragment.getChildFragmentManager()); } public void addTab(@NonNull FragmentCreator fragmentCreator, @Nullable String title) { mFragmentCreatorList.add(fragmentCreator); mTitleList.add(title); } @NonNull @Override public Fragment getItem(int position) { return mFragmentCreatorList.get(position).createFragment(); } @Override public int getCount() { return mFragmentCreatorList.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return mTitleList.get(position); } /** * @deprecated Use {@link #setPageTitle(TabLayout, int, CharSequence)} instead. */ public void setPageTitle(int position, @Nullable CharSequence title) { mTitleList.set(position, title); } public void setPageTitle(@NonNull TabLayout tabLayout, int position, @Nullable CharSequence title) { //noinspection deprecation setPageTitle(position, title); if (position < tabLayout.getTabCount()) { tabLayout.getTabAt(position).setText(title); } } public interface FragmentCreator { @NonNull Fragment createFragment(); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/TabFragmentPagerAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
439
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import androidx.recyclerview.widget.RecyclerView; public class LoadMoreAdapter extends MergeAdapter { private ContentStateAdapter mContentStateAdapter; public LoadMoreAdapter(RecyclerView.Adapter<?>... dataAdapters) { super(appendAdapter(dataAdapters, new ContentStateAdapter())); RecyclerView.Adapter<?>[] adapters = getAdapters(); mContentStateAdapter = (ContentStateAdapter) adapters[adapters.length - 1]; updateHasContentStateItem(); registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onItemRangeChanged(int positionStart, int itemCount) { onChanged(); } @Override public void onItemRangeInserted(int positionStart, int itemCount) { onChanged(); } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { onChanged(); } @Override public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { onChanged(); } @Override public void onChanged() { updateHasContentStateItem(); } }); } private static RecyclerView.Adapter<?>[] appendAdapter(RecyclerView.Adapter<?>[] adapters, RecyclerView.Adapter<?> adapter) { RecyclerView.Adapter<?>[] mergedAdapters = new RecyclerView.Adapter<?>[adapters.length + 1]; System.arraycopy(adapters, 0, mergedAdapters, 0, adapters.length); mergedAdapters[adapters.length] = adapter; return mergedAdapters; } private void updateHasContentStateItem() { int count = getItemCount() - mContentStateAdapter.getItemCount(); mContentStateAdapter.setHasItem(count > 0); } public void setLoading(boolean loading) { mContentStateAdapter.setState(loading ? ContentStateLayout.STATE_LOADING : ContentStateLayout.STATE_EMPTY); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/LoadMoreAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
402
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.TintTypedArray; import android.util.AttributeSet; import me.zhanghai.android.douya.R; /** * @deprecated Use {@link NestedRatioHeightRecyclerView} instead for most of the time. */ public class RatioHeightRecyclerView extends RecyclerView { private float mRatio; public RatioHeightRecyclerView(Context context) { super(context); init(null, 0); } public RatioHeightRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public RatioHeightRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } @SuppressLint("RestrictedApi") private void init(AttributeSet attrs, int defStyle) { TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs, R.styleable.RatioHeightRecyclerView, defStyle, 0); String ratio = a.getString(R.styleable.RatioHeightRecyclerView_ratio); if (ratio != null) { int colonIndex = ratio.indexOf(':'); if (colonIndex < 0) { throw new IllegalArgumentException( "ratio should be a string in the form \"width:height\": " + ratio); } int width = Integer.parseInt(ratio.substring(0, colonIndex)); int height = Integer.parseInt(ratio.substring(colonIndex + 1)); mRatio = (float) width / height; } a.recycle(); } public float getRatio() { return mRatio; } public void setRatio(float ratio) { if (mRatio != ratio) { mRatio = ratio; requestLayout(); invalidate(); } } public void setRatio(float width, float height) { setRatio(width / height); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mRatio > 0) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = Math.round(width / mRatio); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { height = Math.max(height, getMinimumHeight()); } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/RatioHeightRecyclerView.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
527
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import androidx.preference.DialogPreference; import android.util.AttributeSet; import com.takisoft.preferencex.PreferenceFragmentCompat; static { } super(context); } super(context, attrs); } super(context, attrs, defStyleAttr); } int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/LicensesDialogPreference.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
97
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import androidx.appcompat.widget.AppCompatButton; import android.util.AttributeSet; public class AnimateCompoundDrawableButton extends AppCompatButton { public AnimateCompoundDrawableButton(Context context) { super(context); } public AnimateCompoundDrawableButton(Context context, AttributeSet attrs) { super(context, attrs); } public AnimateCompoundDrawableButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) { super.setCompoundDrawables(left, top, right, bottom); startIfAnimatable(left); startIfAnimatable(top); startIfAnimatable(right); startIfAnimatable(bottom); } @Override public void setCompoundDrawablesRelative(Drawable start, Drawable top, Drawable end, Drawable bottom) { super.setCompoundDrawablesRelative(start, top, end, bottom); startIfAnimatable(start); startIfAnimatable(top); startIfAnimatable(end); startIfAnimatable(bottom); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); // Makes a copy of the array, however we cannot do this otherwise. for (Drawable drawable : getCompoundDrawables()) { startIfAnimatable(drawable); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); // Makes a copy of the array, however we cannot do this otherwise. for (Drawable drawable : getCompoundDrawables()) { stopIfAnimatable(drawable); } } private void startIfAnimatable(Drawable drawable) { if (drawable instanceof Animatable) { ((Animatable) drawable).start(); } } private void stopIfAnimatable(Drawable drawable) { if (drawable instanceof Animatable) { ((Animatable) drawable).stop(); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/AnimateCompoundDrawableButton.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
464
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import com.google.android.material.textfield.ExpandedHintTextInputLayout; import me.zhanghai.android.materialedittext.MaterialEditText; import me.zhanghai.android.materialedittext.MaterialEditTextBackgroundDrawable; /** * @see me.zhanghai.android.materialedittext.MaterialTextInputLayout */ public class ExpandedHintMaterialTextInputLayout extends ExpandedHintTextInputLayout { private MaterialEditTextBackgroundDrawable mEditTextBackground; public ExpandedHintMaterialTextInputLayout(Context context) { super(context); } public ExpandedHintMaterialTextInputLayout(Context context, AttributeSet attrs) { super(context, attrs); } public ExpandedHintMaterialTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); if (child instanceof MaterialEditText) { // Just throw a ClassCastException if the background of MaterialEditText is not the one // automatically set. mEditTextBackground = (MaterialEditTextBackgroundDrawable) child.getBackground(); } } @Override public void setError(CharSequence error) { super.setError(error); if (mEditTextBackground != null) { mEditTextBackground.setError(!TextUtils.isEmpty(error)); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/ExpandedHintMaterialTextInputLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
318
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.annotation.TargetApi; import android.os.Build; import androidx.core.view.GravityCompat; import androidx.core.view.ViewCompat; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.WindowInsets; import android.widget.FrameLayout; /** * Helper for dispatching transformed insets to children. Also dispatch insets to newly added child. */ // Notice that WindowInsets is immutable. public class DispatchInsetsHelper { private Delegate mDelegate; // TODO: Use Object for compatibility? private WindowInsets mInsets; public DispatchInsetsHelper(Delegate delegate) { mDelegate = delegate; } // Not calling super deliberately. @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { mInsets = insets; ViewGroup viewGroup = mDelegate.getOwner(); int layoutDirection = ViewCompat.getLayoutDirection(viewGroup); for (int i = 0, count = viewGroup.getChildCount(); i < count; ++i) { View child = viewGroup.getChildAt(i); dispatchInsetsToChild(layoutDirection, child, child.getLayoutParams()); } return insets.consumeSystemWindowInsets(); } public void addView(View child, int index, ViewGroup.LayoutParams params) { if (mInsets != null) { dispatchInsetsToChild(child, params); } mDelegate.superAddView(child, index, params); } public boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout) { if (mInsets != null) { dispatchInsetsToChild(child, params); } return mDelegate.superAddViewInLayout(child, index, params, preventRequestLayout); } @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) private void dispatchInsetsToChild(int layoutDirection, View child, ViewGroup.LayoutParams childLayoutParams) { int childGravity = GravityCompat.getAbsoluteGravity( mDelegate.getGravityFromLayoutParams(childLayoutParams), layoutDirection); // In fact equivalent to the algorithm in Gravity.apply(). int childInsetLeft = mInsets.getSystemWindowInsetLeft(); int childInsetRight = mInsets.getSystemWindowInsetRight(); if (childLayoutParams.width != FrameLayout.LayoutParams.MATCH_PARENT) { if ((childGravity & (Gravity.AXIS_PULL_BEFORE << Gravity.AXIS_X_SHIFT)) == 0) { childInsetLeft = 0; } if ((childGravity & (Gravity.AXIS_PULL_AFTER << Gravity.AXIS_X_SHIFT)) == 0) { childInsetRight = 0; } } int childInsetTop = mInsets.getSystemWindowInsetTop(); int childInsetBottom = mInsets.getSystemWindowInsetBottom(); if (childLayoutParams.height != FrameLayout.LayoutParams.MATCH_PARENT) { if ((childGravity & (Gravity.AXIS_PULL_BEFORE << Gravity.AXIS_Y_SHIFT)) == 0) { childInsetTop = 0; } if ((childGravity & (Gravity.AXIS_PULL_AFTER << Gravity.AXIS_Y_SHIFT)) == 0) { childInsetBottom = 0; } } WindowInsets childInsets = mInsets.replaceSystemWindowInsets(childInsetLeft, childInsetTop, childInsetRight, childInsetBottom); child.dispatchApplyWindowInsets(childInsets); } private void dispatchInsetsToChild(View child, ViewGroup.LayoutParams childLayoutParams) { dispatchInsetsToChild(ViewCompat.getLayoutDirection(mDelegate.getOwner()), child, childLayoutParams); } public interface Delegate { int getGravityFromLayoutParams(ViewGroup.LayoutParams layoutParams); ViewGroup getOwner(); void superAddView(View child, int index, ViewGroup.LayoutParams params); boolean superAddViewInLayout(View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/DispatchInsetsHelper.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
824
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import android.util.AttributeSet; import android.view.MotionEvent; public class FlexibleSpaceContentRecyclerView extends RecyclerView implements FlexibleSpaceContentView { private int mScroll; public FlexibleSpaceContentRecyclerView(Context context) { super(context); init(); } public FlexibleSpaceContentRecyclerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public FlexibleSpaceContentRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { // Do not save the current scroll position. Always store scrollY as 0 and delegate // responsibility of saving state to FlexibleSpaceLayout. setSaveEnabled(false); } @Override public boolean onInterceptTouchEvent(MotionEvent e) { return false; } @Override public boolean onTouchEvent(MotionEvent e) { return false; } @Override public void onScrolled(int dx, int dy) { mScroll += dy; } @Override public void scrollTo(int scroll) { scrollBy(0, scroll - mScroll); } public int getScroll() { return mScroll; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/FlexibleSpaceContentRecyclerView.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
296
```java /* * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import androidx.annotation.DrawableRes; import androidx.appcompat.widget.AppCompatImageView; import android.util.AttributeSet; public class SimpleCircleImageView extends AppCompatImageView { private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP; private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888; private static final int COLOR_DRAWABLE_DIMENSION = 2; private final RectF mDrawableRect = new RectF(); private final Matrix mShaderMatrix = new Matrix(); private final Paint mBitmapPaint = new Paint(); private Bitmap mBitmap; private BitmapShader mBitmapShader; private int mBitmapWidth; private int mBitmapHeight; private float mDrawableRadius; private ColorFilter mColorFilter; private boolean mReady; private boolean mSetupPending; public SimpleCircleImageView(Context context) { super(context); init(); } public SimpleCircleImageView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public SimpleCircleImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { super.setScaleType(SCALE_TYPE); mReady = true; if (mSetupPending) { setup(); mSetupPending = false; } } @Override public ScaleType getScaleType() { return SCALE_TYPE; } @Override public void setScaleType(ScaleType scaleType) { if (scaleType != SCALE_TYPE) { throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType)); } } @Override public void setAdjustViewBounds(boolean adjustViewBounds) { if (adjustViewBounds) { throw new IllegalArgumentException("adjustViewBounds not supported."); } } @Override protected void onDraw(Canvas canvas) { if (mBitmap == null) { return; } canvas.drawCircle(getWidth() / 2f, getHeight() / 2f, mDrawableRadius, mBitmapPaint); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); setup(); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); mBitmap = bm; setup(); } @Override public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); mBitmap = getBitmapFromDrawable(drawable); setup(); } @Override public void setImageResource(@DrawableRes int resId) { super.setImageResource(resId); mBitmap = getBitmapFromDrawable(getDrawable()); setup(); } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); mBitmap = uri != null ? getBitmapFromDrawable(getDrawable()) : null; setup(); } @Override public void setColorFilter(ColorFilter colorFilter) { if (mColorFilter != colorFilter) { mColorFilter = colorFilter; mBitmapPaint.setColorFilter(mColorFilter); invalidate(); } } private Bitmap getBitmapFromDrawable(Drawable drawable) { if (drawable == null) { return null; } if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } try { Bitmap bitmap; if (drawable instanceof ColorDrawable) { bitmap = Bitmap.createBitmap(COLOR_DRAWABLE_DIMENSION, COLOR_DRAWABLE_DIMENSION, BITMAP_CONFIG); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (Exception e) { e.printStackTrace(); return null; } } private void setup() { if (!mReady) { mSetupPending = true; return; } if (getWidth() == 0 && getHeight() == 0) { return; } if (mBitmap == null) { invalidate(); return; } mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapPaint.setAntiAlias(true); mBitmapPaint.setShader(mBitmapShader); mBitmapWidth = mBitmap.getWidth(); mBitmapHeight = mBitmap.getHeight(); mDrawableRect.set(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); mDrawableRadius = Math.min(mDrawableRect.height() / 2f, mDrawableRect.width() / 2f); updateShaderMatrix(); invalidate(); } private void updateShaderMatrix() { mShaderMatrix.set(null); float scale; float dx = 0; float dy = 0; if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) { scale = mDrawableRect.height() / (float) mBitmapHeight; dx = (mDrawableRect.width() - mBitmapWidth * scale) / 2f; } else { scale = mDrawableRect.width() / (float) mBitmapWidth; dy = (mDrawableRect.height() - mBitmapHeight * scale) / 2f; } mShaderMatrix.setScale(scale, scale); mShaderMatrix.postTranslate(Math.round(dx + mDrawableRect.left), Math.round(dy + mDrawableRect.top)); mBitmapShader.setLocalMatrix(mShaderMatrix); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/SimpleCircleImageView.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,354
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import androidx.annotation.NonNull; import androidx.appcompat.widget.AppCompatImageButton; import android.util.AttributeSet; import android.view.View; @SuppressLint("MissingSuperCall") @TargetApi(Build.VERSION_CODES.M) public class ForegroundImageButton extends AppCompatImageButton { private ForegroundHelper mForegroundHelper = new ForegroundHelper( new ForegroundHelper.Delegate() { @Override public View getOwner() { return ForegroundImageButton.this; } @Override public int superGetForegroundGravity() { return ForegroundImageButton.super.getForegroundGravity(); } @Override public void superSetForegroundGravity(int foregroundGravity) { ForegroundImageButton.super.setForegroundGravity(foregroundGravity); } @Override public void superSetVisibility(int visibility) { ForegroundImageButton.super.setVisibility(visibility); } @Override public boolean superVerifyDrawable(Drawable who) { return ForegroundImageButton.super.verifyDrawable(who); } @Override public void superJumpDrawablesToCurrentState() { ForegroundImageButton.super.jumpDrawablesToCurrentState(); } @Override public void superDrawableStateChanged() { ForegroundImageButton.super.drawableStateChanged(); } @Override public void superDrawableHotspotChanged(float x, float y) { ForegroundImageButton.super.drawableHotspotChanged(x, y); } @Override public void superSetForeground(Drawable foreground) { ForegroundImageButton.super.setForeground(foreground); } @Override public Drawable superGetForeground() { return ForegroundImageButton.super.getForeground(); } @Override @SuppressLint("WrongCall") public void superOnLayout(boolean changed, int left, int top, int right, int bottom) { ForegroundImageButton.super.onLayout(changed, left, top, right, bottom); } @Override public void superOnSizeChanged(int w, int h, int oldw, int oldh) { ForegroundImageButton.super.onSizeChanged(w, h, oldw, oldh); } @Override public void superDraw(@NonNull Canvas canvas) { ForegroundImageButton.super.draw(canvas); } }); public ForegroundImageButton(Context context) { super(context); init(null, 0, 0); } public ForegroundImageButton(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0, 0); } public ForegroundImageButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr, 0); } private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) { mForegroundHelper.init(getContext(), attrs, defStyleAttr, defStyleRes); } /** * {@inheritDoc} */ @Override public int getForegroundGravity() { return mForegroundHelper.getForegroundGravity(); } /** * {@inheritDoc} */ @Override public void setForegroundGravity(int foregroundGravity) { if (mForegroundHelper == null) { // Can be null during super class initialization. In this case framework has support for // foreground, so simply call super. super.setForegroundGravity(foregroundGravity); } else { mForegroundHelper.setForegroundGravity(foregroundGravity); } } /** * {@inheritDoc} */ @Override public void setVisibility(int visibility) { mForegroundHelper.setVisibility(visibility); } /** * {@inheritDoc} */ @Override protected boolean verifyDrawable(Drawable who) { return mForegroundHelper.verifyDrawable(who); } /** * {@inheritDoc} */ @Override public void jumpDrawablesToCurrentState() { mForegroundHelper.jumpDrawablesToCurrentState(); } /** * {@inheritDoc} */ @Override protected void drawableStateChanged() { mForegroundHelper.drawableStateChanged(); } /** * {@inheritDoc} */ @Override public void drawableHotspotChanged(float x, float y) { mForegroundHelper.drawableHotspotChanged(x, y); } /** * {@inheritDoc} */ @Override public void setForeground(Drawable foreground) { if (mForegroundHelper == null) { // Can be null during super class initialization. In this case framework has support for // foreground, so simply call super. super.setForeground(foreground); } else { mForegroundHelper.setForeground(foreground); } } /** * {@inheritDoc} */ @Override public Drawable getForeground() { return mForegroundHelper.getForeground(); } /** * {@inheritDoc} */ @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { mForegroundHelper.onLayout(changed, left, top, right, bottom); } /** * {@inheritDoc} */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { mForegroundHelper.onSizeChanged(w, h, oldw, oldh); } /** * {@inheritDoc} */ @Override public void draw(@NonNull Canvas canvas) { mForegroundHelper.draw(canvas); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/ForegroundImageButton.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,186
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import androidx.recyclerview.widget.RecyclerView; import android.util.AttributeSet; public class NestedRecyclerView extends RecyclerView { public NestedRecyclerView(Context context) { super(context); init(); } public NestedRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public NestedRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { setFocusableInTouchMode(false); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/NestedRecyclerView.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
126
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import me.zhanghai.android.douya.util.ViewUtils; public class StaticAdapter extends RecyclerView.Adapter<StaticAdapter.ViewHolder> { private int[] mViewReses; public StaticAdapter(int... viewReses) { mViewReses = viewReses; setHasStableIds(true); } @Override public int getItemCount() { return mViewReses.length; } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return position; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(ViewUtils.inflate(mViewReses[viewType], parent)); } @Override public void onBindViewHolder(ViewHolder holder, int position) {} static class ViewHolder extends RecyclerView.ViewHolder { public ViewHolder(View itemView) { super(itemView); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/StaticAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
231
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.drawable.shapes.Shape; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; public class StarShape extends Shape { private int mNumVertices; private float mInnerRadiusRatio; private Path mStar = new Path(); public StarShape(int numVertices, float innerRadiusRatio) { mNumVertices = numVertices; mInnerRadiusRatio = innerRadiusRatio; } @Override protected void onResize(float width, float height) { mStar.rewind(); double radianPerPoint = Math.PI / mNumVertices; float halfWidth = width / 2; float halfHeight = height / 2; float halfInnerWidth = mInnerRadiusRatio * halfWidth; float halfInnerHeight = mInnerRadiusRatio * halfHeight; for (int i = 0; i < mNumVertices; ++i) { if (i == 0) { mStar.moveTo(halfWidth, 0); } else { mStar.lineTo(halfWidth + (float) Math.sin(2 * i * radianPerPoint) * halfWidth, halfHeight - (float) Math.cos(2 * i * radianPerPoint) * halfHeight); } mStar.lineTo( halfWidth + (float) Math.sin((2 * i + 1) * radianPerPoint) * halfInnerWidth, halfHeight - (float) Math.cos((2 * i + 1) * radianPerPoint) * halfInnerHeight); } mStar.close(); } // Star is not a convex shape. //@RequiresApi(Build.VERSION_CODES.LOLLIPOP) //@Override //public void getOutline(@NonNull Outline outline) { // outline.setConvexPath(mStar); //} @Override public void draw(Canvas canvas, Paint paint) { canvas.drawPath(mStar, paint); } @Override public StarShape clone() throws CloneNotSupportedException { StarShape polygonShape = (StarShape) super.clone(); polygonShape.mStar = new Path(mStar); return polygonShape; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/StarShape.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
488
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; /* * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.provider.Settings; import androidx.core.util.ObjectsCompat; import androidx.preference.Preference; import android.text.TextUtils; import android.util.AttributeSet; import com.takisoft.preferencex.PreferenceFragmentCompat; /** * A {@link Preference} that allows the user to choose a ringtone from those on the device. * The chosen ringtone's URI will be persisted as a string. * <p> * If the user chooses the "Default" item, the saved string will be one of * {@link Settings.System#DEFAULT_RINGTONE_URI}, * {@link Settings.System#DEFAULT_NOTIFICATION_URI}, or * {@link Settings.System#DEFAULT_ALARM_ALERT_URI}. If the user chooses the "Silent" * item, the saved string will be an empty string. * * @attr ref android.R.styleable#RingtonePreference_ringtoneType * @attr ref android.R.styleable#RingtonePreference_showDefault * @attr ref android.R.styleable#RingtonePreference_showSilent */ public class RingtonePreference extends Preference { private static final int[] COM_ANDROID_INTERNAL_R_STYLEABLE_RINGTONE_PREFERENCE = { android.R.attr.ringtoneType, android.R.attr.showDefault, android.R.attr.showSilent }; private static final int your_sha256_hashPE = 0; private static final int your_sha256_hashT = 1; private static final int your_sha256_hash = 2; private int mRingtoneType = RingtoneManager.TYPE_RINGTONE; private boolean mShowDefault = true; private boolean mShowSilent = true; private Uri mRingtoneUri; private boolean mRingtoneSet; static { PreferenceFragmentCompat.registerPreferenceFragment(RingtonePreference.class, RingtonePreferenceActivityFragmentCompat.class); } public RingtonePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(attrs, defStyleAttr, defStyleRes); } public RingtonePreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr, 0); } public RingtonePreference(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0, 0); } public RingtonePreference(Context context) { super(context); init(null, 0, 0); } private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) { TypedArray a = getContext().obtainStyledAttributes(attrs, COM_ANDROID_INTERNAL_R_STYLEABLE_RINGTONE_PREFERENCE, defStyleAttr, defStyleRes); //noinspection ResourceType mRingtoneType = a.getInt(your_sha256_hashPE, mRingtoneType); //noinspection ResourceType mShowDefault = a.getBoolean( your_sha256_hashT, mShowDefault); //noinspection ResourceType mShowSilent = a.getBoolean(your_sha256_hash, mShowSilent); a.recycle(); } /** * Returns the sound type(s) that are shown in the picker. * * @return The sound type(s) that are shown in the picker. * @see #setRingtoneType(int) */ public int getRingtoneType() { return mRingtoneType; } /** * Sets the sound type(s) that are shown in the picker. * * @param type The sound type(s) that are shown in the picker. * @see RingtoneManager#EXTRA_RINGTONE_TYPE */ public void setRingtoneType(int type) { mRingtoneType = type; } /** * Returns whether to a show an item for the default sound/ringtone. * * @return Whether to show an item for the default sound/ringtone. */ public boolean getShowDefault() { return mShowDefault; } /** * Sets whether to show an item for the default sound/ringtone. The default * to use will be deduced from the sound type(s) being shown. * * @param showDefault Whether to show the default or not. * @see RingtoneManager#EXTRA_RINGTONE_SHOW_DEFAULT */ public void setShowDefault(boolean showDefault) { mShowDefault = showDefault; } /** * Returns whether to a show an item for 'Silent'. * * @return Whether to show an item for 'Silent'. */ public boolean getShowSilent() { return mShowSilent; } /** * Sets whether to show an item for 'Silent'. * * @param showSilent Whether to show 'Silent'. * @see RingtoneManager#EXTRA_RINGTONE_SHOW_SILENT */ public void setShowSilent(boolean showSilent) { mShowSilent = showSilent; } @Override public CharSequence getSummary() { CharSequence summary = super.getSummary(); if (!TextUtils.isEmpty(summary)) { Uri ringtoneUri = getRingtoneUri(); String ringtoneTitle = ""; if (ringtoneUri != null) { Context context = getContext(); Ringtone ringtone = RingtoneManager.getRingtone(context, ringtoneUri); if (ringtone != null) { ringtoneTitle = ringtone.getTitle(context); } } return String.format(summary.toString(), ringtoneTitle); } else { return summary; } } @Override protected void onClick() { getPreferenceManager().showDialog(this); } public Intent makeRingtonePickerIntent() { Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); onPrepareRingtonePickerIntent(intent); return intent; } /** * Prepares the intent to launch the ringtone picker. This can be modified * to adjust the parameters of the ringtone picker. * * @param ringtonePickerIntent The ringtone picker intent that can be * modified by putting extras. */ protected void onPrepareRingtonePickerIntent(Intent ringtonePickerIntent) { ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, getRingtoneUri()); ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, mShowDefault); if (mShowDefault) { ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(getRingtoneType())); } ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, mShowSilent); ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, mRingtoneType); ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, getTitle()); //ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_AUDIO_ATTRIBUTES_FLAGS, // AudioAttributes.FLAG_BYPASS_INTERRUPTION_POLICY); } /** * Sets the URI of the ringtone. Can return null to indicate no ringtone. * * @param ringtoneUri The URI of the ringtone. */ public void setRingtoneUri(Uri ringtoneUri) { // Always persist/notify the first time. boolean changed = !ObjectsCompat.equals(mRingtoneUri, ringtoneUri); if (changed || !mRingtoneSet) { mRingtoneUri = ringtoneUri; mRingtoneSet = true; persistString(ringtoneUri != null ? ringtoneUri.toString() : ""); if (changed) { notifyChanged(); } } } /** * Returns the URI of the ringtone. Can return null to indicate no ringtone. * * @return The URI of the ringtone */ public Uri getRingtoneUri() { return mRingtoneUri; } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getString(index); } @Override protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) { if (restorePersistedValue) { String persistedRingtoneString = getPersistedString(null); if (persistedRingtoneString != null) { setRingtoneUri(!TextUtils.isEmpty(persistedRingtoneString) ? Uri.parse(persistedRingtoneString) : null); } else { setRingtoneUri(mRingtoneUri); } } else { String defaultValueString = (String) defaultValue; setRingtoneUri(!TextUtils.isEmpty(defaultValueString) ? Uri.parse(defaultValueString) : null); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/RingtonePreference.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,953
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import org.threeten.bp.ZonedDateTime; import org.threeten.bp.format.DateTimeParseException; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.LogUtils; import me.zhanghai.android.douya.util.TimeUtils; import me.zhanghai.android.douya.util.ViewUtils; public class JoinTimeLocationAutoGoneTextView extends TimeTextView { private String mLocation; public JoinTimeLocationAutoGoneTextView(Context context) { super(context); } public JoinTimeLocationAutoGoneTextView(Context context, AttributeSet attrs) { super(context, attrs); } public JoinTimeLocationAutoGoneTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void setDoubanTime(String doubanTime) { throw new UnsupportedOperationException("Use setJoinTimeAndLocation() instead."); } public void setJoinTimeAndLocation(String doubanTime, String location) { mLocation = location; try { setTime(TimeUtils.parseDoubanDateTime(doubanTime)); } catch (DateTimeParseException e) { LogUtils.e("Unable to parse date time: " + doubanTime); e.printStackTrace(); setTimeText(doubanTime); } } @Override protected String formatTime(ZonedDateTime time) { return TimeUtils.formatDate(time, getContext()); } @Override protected void setTimeText(String timeText) { String text; if (!TextUtils.isEmpty(mLocation)) { text = getContext().getString(R.string.profile_join_time_location_format, timeText, mLocation); } else { text = getContext().getString(R.string.profile_join_time_format, timeText); } setText(text); } @Override public void setText(CharSequence text, BufferType type) { super.setText(text, type); ViewUtils.setVisibleOrGone(this, !TextUtils.isEmpty(text)); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/JoinTimeLocationAutoGoneTextView.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
452
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageButton; import android.util.AttributeSet; public class GetOnLongClickListenerImageButton extends AppCompatImageButton { private OnLongClickListener mOnLongClickListener; public GetOnLongClickListenerImageButton(Context context) { super(context); } public GetOnLongClickListenerImageButton(Context context, AttributeSet attrs) { super(context, attrs); } public GetOnLongClickListenerImageButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public OnLongClickListener getOnLongClickListener() { return mOnLongClickListener; } @Override public void setOnLongClickListener(@Nullable OnLongClickListener listener) { super.setOnLongClickListener(listener); mOnLongClickListener = listener; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/GetOnLongClickListenerImageButton.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
188
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.annotation.SuppressLint; import android.content.Context; import androidx.appcompat.widget.TintTypedArray; import android.util.AttributeSet; import android.view.View; public class MaxDimensionHelper { private static final int[] STYLEABLE = { android.R.attr.maxWidth, android.R.attr.maxHeight }; private static final int STYLEABLE_ANDROID_MAX_WIDTH = 0; private static final int STYLEABLE_ANDROID_MAX_HEIGHT = 1; private Delegate mDelegate; private int mMaxWidth; private int mMaxHeight; public MaxDimensionHelper(Delegate delegate) { mDelegate = delegate; } @SuppressLint("RestrictedApi") public void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { TintTypedArray a = TintTypedArray.obtainStyledAttributes(context, attrs, STYLEABLE, defStyleAttr, defStyleRes); mMaxWidth = a.getDimensionPixelSize(STYLEABLE_ANDROID_MAX_WIDTH, -1); mMaxHeight = a.getDimensionPixelSize(STYLEABLE_ANDROID_MAX_HEIGHT, -1); a.recycle(); } public void onMeasure(int widthSpec, int heightSpec) { if (mMaxWidth >= 0) { widthSpec = View.MeasureSpec.makeMeasureSpec( Math.min(View.MeasureSpec.getSize(widthSpec), mMaxWidth), View.MeasureSpec.getMode(widthSpec)); } if (mMaxHeight >= 0) { heightSpec = View.MeasureSpec.makeMeasureSpec( Math.min(View.MeasureSpec.getSize(heightSpec), mMaxHeight), View.MeasureSpec.getMode(heightSpec)); } mDelegate.superOnMeasure(widthSpec, heightSpec); } public interface Delegate { void superOnMeasure(int widthSpec, int heightSpec); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/MaxDimensionHelper.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
385
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.os.Build; import androidx.appcompat.widget.AppCompatImageView; import android.util.AttributeSet; public class VisibilityAggregatedImageView extends AppCompatImageView { public VisibilityAggregatedImageView(Context context) { super(context); } public VisibilityAggregatedImageView(Context context, AttributeSet attrs) { super(context, attrs); } public VisibilityAggregatedImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { onVisibilityAggregated(visibility == VISIBLE); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/VisibilityAggregatedImageView.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
165
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.ViewUtils; public class ContentStateAdapter extends RecyclerView.Adapter<ContentStateAdapter.ViewHolder> { private boolean mHasItem; private int mState = ContentStateLayout.STATE_EMPTY; private ViewHolder mViewHolder; public ContentStateAdapter() { setHasStableIds(true); } public boolean hasItem() { return mHasItem; } public void setHasItem(boolean hasItem) { if (mHasItem == hasItem) { return; } mHasItem = hasItem; if (mHasItem) { notifyItemInserted(0); } else { notifyItemRemoved(0); } } public void setState(int state) { if (mState == state) { return; } mState = state; if (mHasItem) { if (mViewHolder != null) { onBindViewHolder(mViewHolder, 0); } else { notifyItemChanged(0); } } } @Override public int getItemCount() { return mHasItem ? 1 : 0; } @Override public long getItemId(int position) { return 0; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { ViewHolder holder = new ViewHolder(ViewUtils.inflate(R.layout.content_state_item, parent)); ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams(); if (layoutParams instanceof StaggeredGridLayoutManager.LayoutParams) { StaggeredGridLayoutManager.LayoutParams staggeredGridLayoutParams = (StaggeredGridLayoutManager.LayoutParams) layoutParams; staggeredGridLayoutParams.setFullSpan(true); } holder.errorText.setText(R.string.load_error); return holder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // HACK: There's a glitch on first frame of progress bar. holder.contentStateLayout.setAnimationEnabled(mState == ContentStateLayout.STATE_LOADING); holder.contentStateLayout.setState(mState); mViewHolder = holder; } @Override public void onViewRecycled(@NonNull ViewHolder holder) { mViewHolder = null; } static class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.content_state) public ContentStateLayout contentStateLayout; @BindView(R.id.error) public TextView errorText; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/ContentStateAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
603
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import androidx.annotation.Nullable; import androidx.core.view.GestureDetectorCompat; import androidx.appcompat.widget.Toolbar; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; public class DoubleClickToolbar extends Toolbar { private GestureDetectorCompat mGestureDetectorCompat; private OnDoubleClickListener mOnDoubleClickListener; public DoubleClickToolbar(Context context) { super(context); init(); } public DoubleClickToolbar(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public DoubleClickToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mGestureDetectorCompat = new GestureDetectorCompat(getContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent event) { if (mOnDoubleClickListener != null) { return mOnDoubleClickListener.onDoubleClick(DoubleClickToolbar.this); } return false; } }); mGestureDetectorCompat.setIsLongpressEnabled(false); } @Override public boolean onTouchEvent(MotionEvent event) { boolean handled = super.onTouchEvent(event); mGestureDetectorCompat.onTouchEvent(event); return handled; } public void setOnDoubleClickListener(OnDoubleClickListener listener) { mOnDoubleClickListener = listener; } public interface OnDoubleClickListener { boolean onDoubleClick(View view); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/DoubleClickToolbar.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
336
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.Collection; import java.util.List; public abstract class SimpleAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> { @NonNull private final List<T> mList = new ArrayList<>(); public SimpleAdapter() { this(null); } public SimpleAdapter(@Nullable List<T> list) { if (list != null) { mList.addAll(list); } } @NonNull public List<T> getList() { return mList; } public void addAll(@NonNull Collection<? extends T> collection) { int oldSize = mList.size(); mList.addAll(collection); notifyItemRangeInserted(oldSize, collection.size()); } public void replace(@NonNull Collection<? extends T> collection) { mList.clear(); mList.addAll(collection); notifyDataSetChanged(); } public void add(int position, @Nullable T item) { mList.add(position, item); notifyItemInserted(position); } public void add(@Nullable T item) { add(mList.size(), item); } public void set(int position, @Nullable T item) { mList.set(position, item); notifyItemChanged(position); } @Nullable public T remove(int position) { T item = mList.remove(position); notifyItemRemoved(position); return item; } public void clear() { int oldSize = mList.size(); mList.clear(); notifyItemRangeRemoved(0, oldSize); } public int findPositionById(long id) { int count = getItemCount(); for (int i = 0; i < count; ++i) { if (getItemId(i) == id) { return i; } } return RecyclerView.NO_POSITION; } public void notifyItemChangedById(long id) { int position = findPositionById(id); if (position != RecyclerView.NO_POSITION) { notifyItemChanged(position); } } @Nullable public T removeById(long id) { int position = findPositionById(id); if (position != RecyclerView.NO_POSITION) { return remove(position); } else { return null; } } @Nullable public T getItem(int position) { return mList.get(position); } @Override public int getItemCount() { return mList.size(); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/SimpleAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
539
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.util.AttributeSet; import android.view.View; public class FlexibleSpaceContentLayout extends ContentStateLayout implements FlexibleSpaceContentView { public FlexibleSpaceContentLayout(Context context) { super(context); } public FlexibleSpaceContentLayout(Context context, AttributeSet attrs) { super(context, attrs); } public FlexibleSpaceContentLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public FlexibleSpaceContentLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override public int getScroll() { View contentView = getContentView(); if (contentView instanceof FlexibleSpaceContentView) { return ((FlexibleSpaceContentView) contentView).getScroll(); } else { return contentView.getScrollY(); } } @Override public void scrollTo(int scroll) { View contentView = getContentView(); if (contentView instanceof FlexibleSpaceContentView) { ((FlexibleSpaceContentView) contentView).scrollTo(scroll); } else { contentView.scrollTo(0, scroll); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/FlexibleSpaceContentLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
263
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.os.Build; import android.util.AttributeSet; /** * An ImageView that measures with a ratio. Also sets scaleType to centerCrop. */ public class RatioImageView extends AdjustViewBoundsImageView { private float mRatio; public RatioImageView(Context context) { super(context); init(); } public RatioImageView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { setScaleType(ScaleType.CENTER_CROP); } public float getRatio() { return mRatio; } public void setRatio(float ratio) { if (mRatio != ratio) { mRatio = ratio; requestLayout(); invalidate(); } } public void setRatio(float width, float height) { setRatio(width / height); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mRatio > 0) { if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) { int height = MeasureSpec.getSize(heightMeasureSpec); int width = Math.round(mRatio * height); width = Math.max(width, getSuggestedMinimumWidth()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { width = Math.min(width, getMaxWidth()); } widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); } else { int width = MeasureSpec.getSize(widthMeasureSpec); int height = Math.round(width / mRatio); height = Math.max(height, getSuggestedMinimumHeight()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { height = Math.min(height, getMaxHeight()); } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/RatioImageView.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
448
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import androidx.recyclerview.widget.RecyclerView; public class BarrierAdapter extends MergeAdapter { private BarrierDataAdapter mDataAdapter; private ContentStateAdapter mContentStateAdapter; private boolean mHasError; public BarrierAdapter(BarrierDataAdapter dataAdapter) { super(dataAdapter, new ContentStateAdapter()); mDataAdapter = dataAdapter; RecyclerView.Adapter<?>[] adapters = getAdapters(); mContentStateAdapter = (ContentStateAdapter) adapters[adapters.length - 1]; updateContentState(); registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onItemRangeChanged(int positionStart, int itemCount) { onChanged(); } @Override public void onItemRangeInserted(int positionStart, int itemCount) { onChanged(); } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { onChanged(); } @Override public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { onChanged(); } @Override public void onChanged() { updateContentState(); } }); } public void setError() { mHasError = true; updateContentState(); } private void updateContentState() { int count = mDataAdapter.getItemCount(); boolean hasItem = count > 0 && count < mDataAdapter.getTotalItemCount(); mContentStateAdapter.setHasItem(hasItem); if (!hasItem) { mContentStateAdapter.setState(ContentStateLayout.STATE_EMPTY); mHasError = false; } else { if (mHasError) { mContentStateAdapter.setState(ContentStateLayout.STATE_ERROR); } else { mContentStateAdapter.setState(ContentStateLayout.STATE_LOADING); } } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/BarrierAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
392
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.photo.content; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import me.zhanghai.android.douya.network.api.ApiRequest; import me.zhanghai.android.douya.network.api.ApiService; import me.zhanghai.android.douya.network.api.info.frodo.CollectableItem; import me.zhanghai.android.douya.network.api.info.frodo.PhotoList; import me.zhanghai.android.douya.util.FragmentUtils; public class ItemPhotoListResource extends BasePhotoListResource { private static final String KEY_PREFIX = ItemPhotoListResource.class.getName() + '.'; private static final String EXTRA_ITEM_TYPE = KEY_PREFIX + "item_type"; private static final String EXTRA_ITEM_ID = KEY_PREFIX + "item_id"; private CollectableItem.Type mItemType; private long mItemId; private static final String FRAGMENT_TAG_DEFAULT = ItemPhotoListResource.class.getName(); private static ItemPhotoListResource newInstance(CollectableItem.Type itemType, long itemId) { //noinspection deprecation return new ItemPhotoListResource().setArguments(itemType, itemId); } public static ItemPhotoListResource attachTo(CollectableItem.Type itemType, long itemId, Fragment fragment, String tag, int requestCode) { FragmentActivity activity = fragment.getActivity(); ItemPhotoListResource instance = FragmentUtils.findByTag(activity, tag); if (instance == null) { instance = newInstance(itemType, itemId); FragmentUtils.add(instance, activity, tag); } instance.setTarget(fragment, requestCode); return instance; } public static ItemPhotoListResource attachTo(CollectableItem.Type itemType, long itemId, Fragment fragment) { return attachTo(itemType, itemId, fragment, FRAGMENT_TAG_DEFAULT, REQUEST_CODE_INVALID); } /** * @deprecated Use {@code attachTo()} instead. */ public ItemPhotoListResource() {} protected ItemPhotoListResource setArguments(CollectableItem.Type itemType, long itemId) { FragmentUtils.getArgumentsBuilder(this) .putSerializable(EXTRA_ITEM_TYPE, itemType) .putLong(EXTRA_ITEM_ID, itemId); return this; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mItemType = (CollectableItem.Type) getArguments().getSerializable(EXTRA_ITEM_TYPE); mItemId = getArguments().getLong(EXTRA_ITEM_ID); } @Override protected ApiRequest<PhotoList> onCreateRequest(Integer start, Integer count) { return ApiService.getInstance().getItemPhotoList(mItemType, mItemId, start, count); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/photo/content/ItemPhotoListResource.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
567
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.ui; import android.content.Context; import android.content.res.Resources; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.ThemedSpinnerAdapter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; public class ArrayAdapterCompat<T> extends ArrayAdapter<T> implements ThemedSpinnerAdapter { /* * @see ArrayAdapter#mDropDownResource */ private int mDropDownResource; /* * @see ArrayAdapter#mFieldId */ private int mFieldId; private ThemedSpinnerAdapter.Helper mHelper; /** * {@inheritDoc} */ public ArrayAdapterCompat(@NonNull Context context, int resource) { super(context, resource); init(resource, 0); } /** * {@inheritDoc} */ public ArrayAdapterCompat(@NonNull Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId); init(resource, textViewResourceId); } /** * {@inheritDoc} */ public ArrayAdapterCompat(@NonNull Context context, int resource, @NonNull T[] objects) { super(context, resource, objects); init(resource, 0); } /** * {@inheritDoc} */ public ArrayAdapterCompat(@NonNull Context context, int resource, int textViewResourceId, @NonNull T[] objects) { super(context, resource, textViewResourceId, objects); init(resource, textViewResourceId); } /** * {@inheritDoc} */ public ArrayAdapterCompat(@NonNull Context context, int resource, @NonNull List<T> objects) { super(context, resource, objects); init(resource, 0); } /** * {@inheritDoc} */ public ArrayAdapterCompat(@NonNull Context context, int resource, int textViewResourceId, @NonNull List<T> objects) { super(context, resource, textViewResourceId, objects); init(resource, textViewResourceId); } private void init(int resource, int textViewResourceId) { mDropDownResource = resource; mFieldId = textViewResourceId; mHelper = new ThemedSpinnerAdapter.Helper(getContext()); } /** * {@inheritDoc} */ @Override public void setDropDownViewResource(int resource) { super.setDropDownViewResource(resource); mDropDownResource = resource; } /** * {@inheritDoc} */ @Override public void setDropDownViewTheme(@Nullable Resources.Theme theme) { mHelper.setDropDownViewTheme(theme); } /** * {@inheritDoc} */ @Nullable @Override public Resources.Theme getDropDownViewTheme() { return mHelper.getDropDownViewTheme(); } /** * {@inheritDoc} */ @Override public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = mHelper.getDropDownViewInflater(); return createViewFromResource(inflater, position, convertView, parent, mDropDownResource); } /* * @see ArrayAdapter#createViewFromResource(LayoutInflater, int, View, ViewGroup, int) */ @NonNull private View createViewFromResource(@NonNull LayoutInflater inflater, int position, @Nullable View convertView, @NonNull ViewGroup parent, int resource) { final View view; final TextView text; if (convertView == null) { view = inflater.inflate(resource, parent, false); } else { view = convertView; } try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; } else { // Otherwise, find the TextView field within the layout text = view.findViewById(mFieldId); if (text == null) { throw new RuntimeException("Failed to find view with ID " + getContext().getResources().getResourceName(mFieldId) + " in item layout"); } } } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); } final T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence) item); } else { text.setText(item.toString()); } return view; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/ui/ArrayAdapterCompat.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
955
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.review.content; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import me.zhanghai.android.douya.network.api.ApiRequest; import me.zhanghai.android.douya.network.api.ApiService; import me.zhanghai.android.douya.network.api.info.frodo.ReviewList; import me.zhanghai.android.douya.util.FragmentUtils; public class UserReviewListResource extends BaseReviewListResource { private static final String KEY_PREFIX = UserReviewListResource.class.getName() + '.'; private final String EXTRA_USER_ID_OR_UID = KEY_PREFIX + "user_id_or_uid"; private String mUserIdOrUid; private static final String FRAGMENT_TAG_DEFAULT = UserReviewListResource.class.getName(); private static UserReviewListResource newInstance(String userIdOrUid) { //noinspection deprecation return new UserReviewListResource().setArguments(userIdOrUid); } public static UserReviewListResource attachTo(String userIdOrUid, Fragment fragment, String tag, int requestCode) { FragmentActivity activity = fragment.getActivity(); UserReviewListResource instance = FragmentUtils.findByTag(activity, tag); if (instance == null) { instance = newInstance(userIdOrUid); FragmentUtils.add(instance, activity, tag); } instance.setTarget(fragment, requestCode); return instance; } public static UserReviewListResource attachTo(String userIdOrUid, Fragment fragment) { return attachTo(userIdOrUid, fragment, FRAGMENT_TAG_DEFAULT, REQUEST_CODE_INVALID); } /** * @deprecated Use {@code attachTo()} instead. */ public UserReviewListResource() {} protected UserReviewListResource setArguments(String userIdOrUid) { FragmentUtils.getArgumentsBuilder(this) .putString(EXTRA_USER_ID_OR_UID, userIdOrUid); return this; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUserIdOrUid = getArguments().getString(EXTRA_USER_ID_OR_UID); } @Override protected ApiRequest<ReviewList> onCreateRequest(Integer start, Integer count) { return ApiService.getInstance().getUserReviewList(mUserIdOrUid, start, count); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/review/content/UserReviewListResource.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
480
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.photo.content; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.Collections; import java.util.List; import me.zhanghai.android.douya.content.MoreBaseListResourceFragment; import me.zhanghai.android.douya.eventbus.PhotoDeletedEvent; import me.zhanghai.android.douya.network.api.ApiError; import me.zhanghai.android.douya.network.api.info.frodo.Photo; import me.zhanghai.android.douya.network.api.info.frodo.PhotoList; public abstract class BasePhotoListResource extends MoreBaseListResourceFragment<PhotoList, Photo> { @Override protected void onLoadStarted() { getListener().onLoadPhotoListStarted(getRequestCode()); } @Override protected void onLoadFinished(boolean more, int count, boolean successful, List<Photo> response, ApiError error) { if (successful) { if (more) { append(response); getListener().onLoadPhotoListFinished(getRequestCode()); getListener().onPhotoListAppended(getRequestCode(), Collections.unmodifiableList(response)); } else { set(response); getListener().onLoadPhotoListFinished(getRequestCode()); getListener().onPhotoListChanged(getRequestCode(), Collections.unmodifiableList(get())); } } else { getListener().onLoadPhotoListFinished(getRequestCode()); getListener().onLoadPhotoListError(getRequestCode(), error); } } protected void appendAndNotifyListener(List<Photo> photoList) { append(photoList); getListener().onPhotoListAppended(getRequestCode(), photoList); } @Subscribe(threadMode = ThreadMode.POSTING) public void onPhotoDeleted(PhotoDeletedEvent event) { if (event.isFromMyself(this) || isEmpty()) { return; } List<Photo> photoList = get(); for (int i = 0, size = photoList.size(); i < size; ) { Photo photo = photoList.get(i); if (photo.id == event.photoId) { photoList.remove(i); getListener().onPhotoRemoved(getRequestCode(), i); --size; } else { ++i; } } } private Listener getListener() { return (Listener) getTarget(); } public interface Listener { void onLoadPhotoListStarted(int requestCode); void onLoadPhotoListFinished(int requestCode); void onLoadPhotoListError(int requestCode, ApiError error); /** * @param newPhotoList Unmodifiable. */ void onPhotoListChanged(int requestCode, List<Photo> newPhotoList); /** * @param appendedPhotoList Unmodifiable. */ void onPhotoListAppended(int requestCode, List<Photo> appendedPhotoList); void onPhotoRemoved(int requestCode, int position); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/photo/content/BasePhotoListResource.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
628
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.review.content; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import me.zhanghai.android.douya.network.api.ApiRequest; import me.zhanghai.android.douya.network.api.ApiService; import me.zhanghai.android.douya.network.api.info.frodo.CollectableItem; import me.zhanghai.android.douya.network.api.info.frodo.ReviewList; import me.zhanghai.android.douya.util.FragmentUtils; public class ItemReviewListResource extends BaseReviewListResource { private static final String KEY_PREFIX = ItemReviewListResource.class.getName() + '.'; private static final String EXTRA_ITEM_TYPE = KEY_PREFIX + "item_type"; private static final String EXTRA_ITEM_ID = KEY_PREFIX + "item_id"; private CollectableItem.Type mItemType; private long mItemId; private static final String FRAGMENT_TAG_DEFAULT = ItemReviewListResource.class.getName(); private static ItemReviewListResource newInstance(CollectableItem.Type itemType, long itemId) { //noinspection deprecation return new ItemReviewListResource().setArguments(itemType, itemId); } public static ItemReviewListResource attachTo(CollectableItem.Type itemType, long itemId, Fragment fragment, String tag, int requestCode) { FragmentActivity activity = fragment.getActivity(); ItemReviewListResource instance = FragmentUtils.findByTag(activity, tag); if (instance == null) { instance = newInstance(itemType, itemId); FragmentUtils.add(instance, activity, tag); } instance.setTarget(fragment, requestCode); return instance; } public static ItemReviewListResource attachTo(CollectableItem.Type itemType, long itemId, Fragment fragment) { return attachTo(itemType, itemId, fragment, FRAGMENT_TAG_DEFAULT, REQUEST_CODE_INVALID); } /** * @deprecated Use {@code attachTo()} instead. */ public ItemReviewListResource() {} protected ItemReviewListResource setArguments(CollectableItem.Type itemType, long itemId) { FragmentUtils.getArgumentsBuilder(this) .putSerializable(EXTRA_ITEM_TYPE, itemType) .putLong(EXTRA_ITEM_ID, itemId); return this; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mItemType = (CollectableItem.Type) getArguments().getSerializable(EXTRA_ITEM_TYPE); mItemId = getArguments().getLong(EXTRA_ITEM_ID); } @Override protected ApiRequest<ReviewList> onCreateRequest(Integer start, Integer count) { return ApiService.getInstance().getItemReviewList(mItemType, mItemId, start, count); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/review/content/ItemReviewListResource.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
568
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.review.content; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.Collections; import java.util.List; import me.zhanghai.android.douya.content.MoreBaseListResourceFragment; import me.zhanghai.android.douya.eventbus.EventBusUtils; import me.zhanghai.android.douya.eventbus.ReviewDeletedEvent; import me.zhanghai.android.douya.eventbus.ReviewUpdatedEvent; import me.zhanghai.android.douya.network.api.ApiError; import me.zhanghai.android.douya.network.api.info.frodo.SimpleReview; import me.zhanghai.android.douya.network.api.info.frodo.ReviewList; public abstract class BaseReviewListResource extends MoreBaseListResourceFragment<ReviewList, SimpleReview> { @Override protected void onLoadStarted() { getListener().onLoadReviewListStarted(getRequestCode()); } @Override protected void onLoadFinished(boolean more, int count, boolean successful, List<SimpleReview> response, ApiError error) { if (successful) { if (more) { append(response); getListener().onLoadReviewListFinished(getRequestCode()); getListener().onReviewListAppended(getRequestCode(), Collections.unmodifiableList(response)); } else { set(response); getListener().onLoadReviewListFinished(getRequestCode()); getListener().onReviewListChanged(getRequestCode(), Collections.unmodifiableList(get())); } for (SimpleReview review : response) { EventBusUtils.postAsync(new ReviewUpdatedEvent(review, this)); } } else { getListener().onLoadReviewListFinished(getRequestCode()); getListener().onLoadReviewListError(getRequestCode(), error); } } @Subscribe(threadMode = ThreadMode.POSTING) public void onReviewUpdated(ReviewUpdatedEvent event) { if (event.isFromMyself(this) || isEmpty()) { return; } List<SimpleReview> reviewList = get(); for (int i = 0, size = reviewList.size(); i < size; ++i) { SimpleReview review = reviewList.get(i); if (review.id == event.review.id) { reviewList.set(i, event.review); getListener().onReviewChanged(getRequestCode(), i, reviewList.get(i)); } } } @Subscribe(threadMode = ThreadMode.POSTING) public void onReviewDeleted(ReviewDeletedEvent event) { if (event.isFromMyself(this) || isEmpty()) { return; } List<SimpleReview> reviewList = get(); for (int i = 0, size = reviewList.size(); i < size; ) { SimpleReview review = reviewList.get(i); if (review.id == event.reviewId) { reviewList.remove(i); getListener().onReviewRemoved(getRequestCode(), i); --size; } else { ++i; } } } protected Listener getListener() { return (Listener) getTarget(); } public interface Listener { void onLoadReviewListStarted(int requestCode); void onLoadReviewListFinished(int requestCode); void onLoadReviewListError(int requestCode, ApiError error); /** * @param newReviewList Unmodifiable. */ void onReviewListChanged(int requestCode, List<SimpleReview> newReviewList); /** * @param appendedReviewList Unmodifiable. */ void onReviewListAppended(int requestCode, List<SimpleReview> appendedReviewList); void onReviewChanged(int requestCode, int position, SimpleReview newReview); void onReviewRemoved(int requestCode, int position); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/review/content/BaseReviewListResource.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
805
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.ui; import android.content.Context; import android.content.Intent; public class FollowerListActivity extends FollowshipListActivity { public static Intent makeIntent(String userIdOrUid, Context context) { return new Intent(context, FollowerListActivity.class) .putExtra(EXTRA_USER_ID_OR_UID, userIdOrUid); } @Override protected FollowshipListActivityFragment onCreateActivityFragment(String userIdOrUid) { return FollowerListActivityFragment.newInstance(userIdOrUid); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/ui/FollowerListActivity.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
122
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.ui; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import me.zhanghai.android.douya.util.FragmentUtils; public abstract class FollowshipListActivity extends AppCompatActivity { private static final String KEY_PREFIX = FollowshipListActivity.class.getName() + '.'; protected static final String EXTRA_USER_ID_OR_UID = KEY_PREFIX + "user_id_or_uid"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Calls ensureSubDecor(). findViewById(android.R.id.content); if (savedInstanceState == null) { String userIdOrUid = getIntent().getStringExtra(EXTRA_USER_ID_OR_UID); FragmentUtils.add(onCreateActivityFragment(userIdOrUid), this, android.R.id.content); } } abstract protected FollowshipListActivityFragment onCreateActivityFragment(String userIdOrUid); } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/ui/FollowshipListActivity.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
189
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.ui; import android.os.Bundle; import me.zhanghai.android.douya.network.api.info.frodo.SimpleUser; import me.zhanghai.android.douya.ui.SimpleAdapter; import me.zhanghai.android.douya.user.ui.BaseUserListFragment; import me.zhanghai.android.douya.user.ui.UserAdapter; import me.zhanghai.android.douya.util.FragmentUtils; public abstract class FollowshipUserListFragment extends BaseUserListFragment { // Not static because we are to be subclassed. private final String KEY_PREFIX = getClass().getName() + '.'; private final String EXTRA_USER_ID_OR_UID = KEY_PREFIX + "user_id_or_uid"; private String mUserIdOrUid; protected FollowshipUserListFragment setArguments(String userIdOrUid) { FragmentUtils.getArgumentsBuilder(this) .putString(EXTRA_USER_ID_OR_UID, userIdOrUid); return this; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUserIdOrUid = getArguments().getString(EXTRA_USER_ID_OR_UID); } @Override protected SimpleAdapter<SimpleUser, ?> onCreateAdapter() { return new UserAdapter(); } protected String getUserIdOrUid() { return mUserIdOrUid; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/ui/FollowshipUserListFragment.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
289
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.ui; import java.util.List; import me.zhanghai.android.douya.content.MoreListResourceFragment; import me.zhanghai.android.douya.followship.content.FollowingListResource; import me.zhanghai.android.douya.network.api.info.frodo.SimpleUser; public class FollowingListFragment extends FollowshipUserListFragment { public static FollowingListFragment newInstance(String userIdOrUid) { //noinspection deprecation return new FollowingListFragment().setArguments(userIdOrUid); } /** * @deprecated Use {@link #newInstance(String)} instead. */ public FollowingListFragment() {} @Override protected FollowingListFragment setArguments(String userIdOrUid) { super.setArguments(userIdOrUid); return this; } @Override protected MoreListResourceFragment<?, List<SimpleUser>> onAttachResource() { return FollowingListResource.attachTo(getUserIdOrUid(), this); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/ui/FollowingListFragment.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
216
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.ui; public class FollowingListActivityFragment extends FollowshipListActivityFragment { public static FollowingListActivityFragment newInstance(String userIdOrUid) { //noinspection deprecation return new FollowingListActivityFragment().setArguments(userIdOrUid); } /** * @deprecated Use {@link #newInstance(String)} instead. */ public FollowingListActivityFragment() {} @Override protected FollowingListActivityFragment setArguments(String userIdOrUid) { super.setArguments(userIdOrUid); return this; } @Override protected FollowshipUserListFragment onCreateListFragment() { return FollowingListFragment.newInstance(getUserIdOrUid()); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/ui/FollowingListActivityFragment.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
157
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.ui; public class FollowerListActivityFragment extends FollowshipListActivityFragment { public static FollowerListActivityFragment newInstance(String userIdOrUid) { //noinspection deprecation return new FollowerListActivityFragment().setArguments(userIdOrUid); } /** * @deprecated Use {@link #newInstance(String)} instead. */ public FollowerListActivityFragment() {} @Override protected FollowerListActivityFragment setArguments(String userIdOrUid) { super.setArguments(userIdOrUid); return this; } @Override protected FollowshipUserListFragment onCreateListFragment() { return FollowerListFragment.newInstance(getUserIdOrUid()); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/ui/FollowerListActivityFragment.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
163
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.ui; import android.content.Context; import android.content.Intent; public class FollowingListActivity extends FollowshipListActivity { public static Intent makeIntent(String userIdOrUid, Context context) { return new Intent(context, FollowingListActivity.class) .putExtra(EXTRA_USER_ID_OR_UID, userIdOrUid); } @Override protected FollowshipListActivityFragment onCreateActivityFragment(String userIdOrUid) { return FollowingListActivityFragment.newInstance(userIdOrUid); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/ui/FollowingListActivity.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
119
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.ui; import java.util.List; import me.zhanghai.android.douya.content.MoreListResourceFragment; import me.zhanghai.android.douya.followship.content.FollowerListResource; import me.zhanghai.android.douya.network.api.info.frodo.SimpleUser; public class FollowerListFragment extends FollowshipUserListFragment { public static FollowerListFragment newInstance(String userIdOrUid) { //noinspection deprecation return new FollowerListFragment().setArguments(userIdOrUid); } /** * @deprecated Use {@link #newInstance(String)} instead. */ public FollowerListFragment() {} @Override protected FollowerListFragment setArguments(String userIdOrUid) { super.setArguments(userIdOrUid); return this; } @Override protected MoreListResourceFragment<?, List<SimpleUser>> onAttachResource() { return FollowerListResource.attachTo(getUserIdOrUid(), this); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/ui/FollowerListFragment.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
221
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.ui; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.FragmentUtils; import me.zhanghai.android.douya.util.TransitionUtils; public abstract class FollowshipListActivityFragment extends Fragment { private static final String KEY_PREFIX = FollowshipListActivityFragment.class.getName() + '.'; private static final String EXTRA_USER_ID_OR_UID = KEY_PREFIX + "user_id_or_uid"; @BindView(R.id.toolbar) Toolbar mToolbar; private String mUserIdOrUid; protected FollowshipListActivityFragment setArguments(String userIdOrUid) { FragmentUtils.getArgumentsBuilder(this) .putString(EXTRA_USER_ID_OR_UID, userIdOrUid); return this; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle arguments = getArguments(); mUserIdOrUid = arguments.getString(EXTRA_USER_ID_OR_UID); setHasOptionsMenu(true); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.followship_list_activity_fragment, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.setSupportActionBar(mToolbar); TransitionUtils.setupTransitionOnActivityCreated(this); if (savedInstanceState == null) { FragmentUtils.add(onCreateListFragment(), this, R.id.followship_list_fragment); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: getActivity().finish(); return true; default: return super.onOptionsItemSelected(item); } } protected String getUserIdOrUid() { return mUserIdOrUid; } abstract protected FollowshipUserListFragment onCreateListFragment(); } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/ui/FollowshipListActivityFragment.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
513
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.content; import me.zhanghai.android.douya.user.content.UserListResource; import me.zhanghai.android.douya.util.FragmentUtils; public abstract class FollowshipUserListResource extends UserListResource { // Not static because we are to be subclassed. private final String KEY_PREFIX = getClass().getName() + '.'; private final String EXTRA_USER_ID_OR_UID = KEY_PREFIX + "user_id_or_uid"; protected FollowshipUserListResource setArguments(String userIdOrUid) { FragmentUtils.getArgumentsBuilder(this) .putString(EXTRA_USER_ID_OR_UID, userIdOrUid); return this; } protected String getUserIdOrUid() { return getArguments().getString(EXTRA_USER_ID_OR_UID); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/content/FollowshipUserListResource.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
174
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.content; import android.content.Context; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.content.ResourceWriterManager; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.util.ToastUtils; public class FollowUserManager extends ResourceWriterManager<FollowUserWriter> { private static class InstanceHolder { public static final FollowUserManager VALUE = new FollowUserManager(); } public static FollowUserManager getInstance() { return InstanceHolder.VALUE; } /** * @deprecated Use {@link #write(User, boolean, Context)} instead. */ public void write(String userIdOrUid, boolean like, Context context) { add(new FollowUserWriter(userIdOrUid, like, this), context); } public boolean write(User user, boolean like, Context context) { if (shouldWrite(user, context)) { add(new FollowUserWriter(user, like, this), context); return true; } else { return false; } } private boolean shouldWrite(User user, Context context) { if (user.isOneself()) { ToastUtils.show(R.string.user_follow_error_cannot_follow_oneself, context); return false; } else { return true; } } public boolean isWriting(String userIdOrUid) { return findWriter(userIdOrUid) != null; } public boolean isWritingFollow(String userIdOrUid) { FollowUserWriter writer = findWriter(userIdOrUid); return writer != null && writer.isFollow(); } private FollowUserWriter findWriter(String userIdOrUid) { for (FollowUserWriter writer : getWriters()) { if (writer.hasUserIdOrUid(userIdOrUid)) { return writer; } } return null; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/content/FollowUserManager.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
414
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.content; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import me.zhanghai.android.douya.network.api.ApiRequest; import me.zhanghai.android.douya.network.api.ApiService; import me.zhanghai.android.douya.network.api.info.frodo.UserList; import me.zhanghai.android.douya.util.FragmentUtils; public class FollowingListResource extends FollowshipUserListResource { private static final String FRAGMENT_TAG_DEFAULT = FollowingListResource.class.getName(); private static FollowingListResource newInstance(String userIdOrUid) { //noinspection deprecation return new FollowingListResource().setArguments(userIdOrUid); } public static FollowingListResource attachTo(String userIdOrUid, Fragment fragment, String tag, int requestCode) { FragmentActivity activity = fragment.getActivity(); FollowingListResource instance = FragmentUtils.findByTag(activity, tag); if (instance == null) { instance = newInstance(userIdOrUid); FragmentUtils.add(instance, activity, tag); } instance.setTarget(fragment, requestCode); return instance; } public static FollowingListResource attachTo(String userIdOrUid, Fragment fragment) { return attachTo(userIdOrUid, fragment, FRAGMENT_TAG_DEFAULT, REQUEST_CODE_INVALID); } /** * @deprecated Use {@code attachTo()} instead. */ public FollowingListResource() {} @Override protected FollowingListResource setArguments(String userIdOrUid) { super.setArguments(userIdOrUid); return this; } @Override protected ApiRequest<UserList> onCreateRequest(Integer start, Integer count) { return ApiService.getInstance().getFollowingList(getUserIdOrUid(), start, count); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/content/FollowingListResource.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
375
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.content; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import me.zhanghai.android.douya.network.api.ApiRequest; import me.zhanghai.android.douya.network.api.ApiService; import me.zhanghai.android.douya.network.api.info.frodo.UserList; import me.zhanghai.android.douya.util.FragmentUtils; public class FollowerListResource extends FollowshipUserListResource { private static final String FRAGMENT_TAG_DEFAULT = FollowerListResource.class.getName(); private static FollowerListResource newInstance(String userIdOrUid) { //noinspection deprecation return new FollowerListResource().setArguments(userIdOrUid); } public static FollowerListResource attachTo(String userIdOrUid, Fragment fragment, String tag, int requestCode) { FragmentActivity activity = fragment.getActivity(); FollowerListResource instance = FragmentUtils.findByTag(activity, tag); if (instance == null) { instance = newInstance(userIdOrUid); FragmentUtils.add(instance, activity, tag); } instance.setTarget(fragment, requestCode); return instance; } public static FollowerListResource attachTo(String userIdOrUid, Fragment fragment) { return attachTo(userIdOrUid, fragment, FRAGMENT_TAG_DEFAULT, REQUEST_CODE_INVALID); } /** * @deprecated Use {@code attachTo()} instead. */ public FollowerListResource() {} @Override protected FollowerListResource setArguments(String userIdOrUid) { super.setArguments(userIdOrUid); return this; } @Override protected ApiRequest<UserList> onCreateRequest(Integer start, Integer count) { return ApiService.getInstance().getFollowerList(getUserIdOrUid(), start, count); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/content/FollowerListResource.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
385
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.followship.content; import android.content.Context; import android.text.TextUtils; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.content.RequestResourceWriter; import me.zhanghai.android.douya.eventbus.EventBusUtils; import me.zhanghai.android.douya.eventbus.UserUpdatedEvent; import me.zhanghai.android.douya.eventbus.UserWriteFinishedEvent; import me.zhanghai.android.douya.eventbus.UserWriteStartedEvent; import me.zhanghai.android.douya.network.api.ApiContract.Response.Error.Codes; import me.zhanghai.android.douya.network.api.ApiError; import me.zhanghai.android.douya.network.api.ApiRequest; import me.zhanghai.android.douya.network.api.ApiService; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.util.LogUtils; import me.zhanghai.android.douya.util.ToastUtils; class FollowUserWriter extends RequestResourceWriter<FollowUserWriter, User> { private String mUserIdOrUid; private User mUser; private boolean mFollow; private FollowUserWriter(String userIdOrUid, User user, boolean follow, FollowUserManager manager) { super(manager); mUserIdOrUid = userIdOrUid; mUser = user; mFollow = follow; EventBusUtils.register(this); } FollowUserWriter(String userIdOrUid, boolean follow, FollowUserManager manager) { this(userIdOrUid, null, follow, manager); } FollowUserWriter(User user, boolean follow, FollowUserManager manager) { this(user.getIdOrUid(), user, follow, manager); } public String getUserIdOrUid() { return mUserIdOrUid; } public boolean hasUserIdOrUid(String userIdOrUid) { return mUser != null ? mUser.isIdOrUid(userIdOrUid) : TextUtils.equals(mUserIdOrUid, userIdOrUid); } public boolean isFollow() { return mFollow; } @Override protected ApiRequest<User> onCreateRequest() { return ApiService.getInstance().follow(mUserIdOrUid, mFollow); } @Override public void onStart() { super.onStart(); EventBusUtils.postAsync(new UserWriteStartedEvent(mUserIdOrUid, this)); } @Override public void onDestroy() { super.onDestroy(); EventBusUtils.unregister(this); } @Override public void onResponse(User response) { ToastUtils.show(mFollow ? R.string.user_follow_successful : R.string.user_unfollow_successful, getContext()); EventBusUtils.postAsync(new UserUpdatedEvent(response, this)); stopSelf(); } @Override public void onErrorResponse(ApiError error) { LogUtils.e(error.toString()); Context context = getContext(); ToastUtils.show(context.getString(mFollow ? R.string.user_follow_failed_format : R.string.user_unfollow_failed_format, ApiError.getErrorString(error, context)), context); boolean notified = false; if (mUser != null && error instanceof ApiError) { // Correct our local state if needed. ApiError apiError = (ApiError) error; Boolean shouldBeFollowed = null; if (apiError.code == Codes.Followship.ALREADY_FOLLOWED) { shouldBeFollowed = true; } else if (apiError.code == Codes.Followship.NOT_FOLLOWED_YET) { shouldBeFollowed = false; } if (shouldBeFollowed != null) { mUser.fixFollowed(shouldBeFollowed); EventBusUtils.postAsync(new UserUpdatedEvent(mUser, this)); notified = true; } } if (!notified) { // Must notify to reset pending status. Off-screen items also needs to be invalidated. EventBusUtils.postAsync(new UserWriteFinishedEvent(mUserIdOrUid, this)); } stopSelf(); } @Subscribe(threadMode = ThreadMode.POSTING) public void onUserUpdated(UserUpdatedEvent event) { if (event.isFromMyself(this)) { return; } //noinspection deprecation if (event.mUser.isIdOrUid(mUserIdOrUid)) { mUserIdOrUid = event.mUser.getIdOrUid(); mUser = event.mUser; } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/followship/content/FollowUserWriter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
958
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.ui; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; /** * Base class for implementing an AppCompatActivity that is used to help implement an * AbstractAccountAuthenticator. If the AbstractAccountAuthenticator needs to use an activity * to handle the request then it can have the activity extend * AppCompatAccountAuthenticatorActivity. * The AbstractAccountAuthenticator passes in the response to the intent using the following: * <pre> * intent.putExtra({@link AccountManager#KEY_ACCOUNT_AUTHENTICATOR_RESPONSE}, response); * </pre> * The activity then sets the result that is to be handed to the response via * {@link #setAccountAuthenticatorResult(Bundle)}. * This result will be sent as the result of the request when the activity finishes. If this * is never set or if it is set to null then error {@link AccountManager#ERROR_CODE_CANCELED} * will be called on the response. */ public abstract class AppCompatAccountAuthenticatorActivity extends AppCompatActivity { private AccountAuthenticatorResponse mAccountAuthenticatorResponse = null; private Bundle mResultBundle = null; /** * Set the result that is to be sent as the result of the request that caused this * Activity to be launched. If result is null or this method is never called then * the request will be canceled. * @param result this is returned as the result of the AbstractAccountAuthenticator request */ public final void setAccountAuthenticatorResult(Bundle result) { mResultBundle = result; } /** * Retreives the AccountAuthenticatorResponse from either the intent of the icicle, if the * icicle is non-zero. * @param icicle the save instance data of this Activity, may be null */ protected void onCreate(Bundle icicle) { super.onCreate(icicle); mAccountAuthenticatorResponse = getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE); if (mAccountAuthenticatorResponse != null) { mAccountAuthenticatorResponse.onRequestContinued(); } } /** * Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present. */ public void finish() { if (mAccountAuthenticatorResponse != null) { // send the result bundle back if set, otherwise send an error. if (mResultBundle != null) { mAccountAuthenticatorResponse.onResult(mResultBundle); } else { mAccountAuthenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED, "canceled"); } mAccountAuthenticatorResponse = null; } super.finish(); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/ui/AppCompatAccountAuthenticatorActivity.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
590
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.ui; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import java.io.IOException; import me.zhanghai.android.douya.account.util.AccountUtils; public class AddAccountActivity extends AppCompatActivity { private static final String KEY_PREFIX = AddAccountActivity.class.getName() + '.'; private static final String EXTRA_ON_ADDED_INTENT = KEY_PREFIX + "on_added_intent"; public static Intent makeIntent(Intent onAddedIntent, Context context) { return new Intent(context, AddAccountActivity.class) .putExtra(EXTRA_ON_ADDED_INTENT, onAddedIntent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { AccountUtils.addAccount(this, new AccountManagerCallback<Bundle>() { @Override public void run(AccountManagerFuture<Bundle> future) { finish(); try { Bundle result = future.getResult(); if (result.containsKey(AccountManager.KEY_ACCOUNT_NAME) && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE)) { // NOTE: // Active account should have been set in // AuthenticatorActivity.onAuthResult() since the mode should be // AUTH_MODE_NEW. Intent onAddedIntent = getIntent() .getParcelableExtra(EXTRA_ON_ADDED_INTENT); startActivity(onAddedIntent); } } catch (AuthenticatorException | IOException | OperationCanceledException e) { e.printStackTrace(); } } }, null); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/ui/AddAccountActivity.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
373
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.ui; import android.accounts.Account; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.account.util.AccountUtils; import me.zhanghai.android.douya.ui.SimpleDialogFragment; public class SelectAccountActivity extends AppCompatActivity implements SimpleDialogFragment.ListenerProvider { private static final String KEY_PREFIX = SelectAccountActivity.class.getName() + '.'; private static final String EXTRA_ON_SELECTED_INTENT = KEY_PREFIX + "on_selected_intent"; private SimpleDialogFragment.Listener mDialogListener; public static Intent makeIntent(Intent onSelectedIntent, Context context) { return new Intent(context, SelectAccountActivity.class) .putExtra(SelectAccountActivity.EXTRA_ON_SELECTED_INTENT, onSelectedIntent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // FIXME: Account list might change; don't use SimpleDialogFragment. final Account[] accounts = AccountUtils.getAccounts(); int numAccounts = accounts.length; String[] accountNames = new String[numAccounts]; for (int i = 0; i < numAccounts; ++i) { accountNames[i] = accounts[i].name; } mDialogListener = new SimpleDialogFragment.Listener() { @Override public void onSingleChoiceItemClicked(int requestCode, int index) { AccountUtils.setActiveAccount(accounts[index]); // Calling finish() before startActivity() makes it work when the Intent is a // launcher one. finish(); Intent onSelectedIntent = getIntent().getParcelableExtra(EXTRA_ON_SELECTED_INTENT); startActivity(onSelectedIntent); } @Override public void onNegativeButtonClicked(int requestCode) { onCancel(requestCode); } @Override public void onCancel(int requestCode) { finish(); } }; if (savedInstanceState == null) { SimpleDialogFragment.makeSingleChoice(R.string.auth_select_account, accountNames, -1, this) .show(this); } } @Override public SimpleDialogFragment.Listener getDialogListener() { return mDialogListener; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/ui/SelectAccountActivity.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
481
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.ui; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import me.zhanghai.android.douya.util.FragmentUtils; public class AuthenticatorActivity extends AppCompatAccountAuthenticatorActivity { private static final String KEY_PREFIX = AuthenticatorActivity.class.getName() + '.'; // NOTE: EXTRA_AUTH_MODE and must be supplied. private static final String EXTRA_AUTH_MODE = KEY_PREFIX + "auth_mode"; private static final String EXTRA_USERNAME = KEY_PREFIX + "username"; public static final String AUTH_MODE_NEW = "new"; public static final String AUTH_MODE_ADD = "add"; public static final String AUTH_MODE_UPDATE = "update"; public static final String AUTH_MODE_CONFIRM = "confirm"; @Retention(RetentionPolicy.SOURCE) @StringDef({ AUTH_MODE_NEW, AUTH_MODE_ADD, AUTH_MODE_CONFIRM, AUTH_MODE_UPDATE }) @interface AuthMode {} public static Intent makeIntent(AccountAuthenticatorResponse response, @AuthMode String authMode, Context context) { return new Intent(context, AuthenticatorActivity.class) .putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response) .putExtra(EXTRA_AUTH_MODE, authMode); } public static Intent makeIntent(AccountAuthenticatorResponse response, @AuthMode String authMode, String username, Context context) { return makeIntent(response, authMode, context) .putExtra(EXTRA_USERNAME, username); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Calls ensureSubDecor(). findViewById(android.R.id.content); if (savedInstanceState == null) { Intent intent = getIntent(); @AuthMode String authMode = intent.getStringExtra(EXTRA_AUTH_MODE); String username = intent.getStringExtra(EXTRA_USERNAME); FragmentUtils.add(AuthenticatorFragment.newInstance(authMode, username), this, android.R.id.content); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/ui/AuthenticatorActivity.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
457
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.info; import me.zhanghai.android.douya.BuildConfig; public class AccountContract { public static final String ACCOUNT_TYPE = BuildConfig.APPLICATION_ID; private static final String SUFFIX_API_V2 = ".api_v2"; private static final String SUFFIX_FRODO = ".frodo"; public static final String AUTH_TOKEN_TYPE_API_V2 = BuildConfig.APPLICATION_ID + SUFFIX_API_V2; public static final String AUTH_TOKEN_TYPE_FRODO = BuildConfig.APPLICATION_ID + SUFFIX_FRODO; public static final String KEY_USER_NAME = BuildConfig.APPLICATION_ID + ".user_name"; public static final String KEY_USER_ID = BuildConfig.APPLICATION_ID + ".user_id"; public static final long INVALID_USER_ID = -1; public static final String KEY_REFRESH_TOKEN_API_V2 = BuildConfig.APPLICATION_ID + ".refresh_token" + SUFFIX_API_V2; public static final String KEY_REFRESH_TOKEN_FRODO = BuildConfig.APPLICATION_ID + ".refresh_token" + SUFFIX_FRODO; public static final String KEY_USER_INFO = BuildConfig.APPLICATION_ID + ".user_info"; private AccountContract() {} } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/info/AccountContract.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
261
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.app; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class AuthenticatorService extends Service { @Override public IBinder onBind(Intent intent) { Authenticator authenticator = new Authenticator(this); return authenticator.getIBinder(); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/app/AuthenticatorService.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
79
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.ui; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import com.google.android.material.textfield.TextInputLayout; import androidx.fragment.app.Fragment; import android.text.TextUtils; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.account.content.AuthenticateRequest; import me.zhanghai.android.douya.account.info.AccountContract; import me.zhanghai.android.douya.account.util.AccountUtils; import me.zhanghai.android.douya.account.util.AuthenticatorUtils; import me.zhanghai.android.douya.link.NotImplementedManager; import me.zhanghai.android.douya.network.api.ApiContract.Response.Error.Codes; import me.zhanghai.android.douya.network.api.ApiError; import me.zhanghai.android.douya.network.api.info.AuthenticationResponse; import me.zhanghai.android.douya.util.FragmentUtils; import me.zhanghai.android.douya.util.LogUtils; import me.zhanghai.android.douya.util.ToastUtils; import me.zhanghai.android.douya.util.ViewUtils; import static me.zhanghai.android.douya.account.ui.AuthenticatorActivity.AUTH_MODE_ADD; import static me.zhanghai.android.douya.account.ui.AuthenticatorActivity.AUTH_MODE_CONFIRM; import static me.zhanghai.android.douya.account.ui.AuthenticatorActivity.AUTH_MODE_NEW; import static me.zhanghai.android.douya.account.ui.AuthenticatorActivity.AUTH_MODE_UPDATE; import static me.zhanghai.android.douya.account.ui.AuthenticatorActivity.AuthMode; public class AuthenticatorFragment extends Fragment implements AuthenticateRequest.Listener { private static final String KEY_PREFIX = AuthenticatorFragment.class.getName() + '.'; private static final String EXTRA_AUTH_MODE = KEY_PREFIX + "auth_mode"; private static final String EXTRA_USERNAME = KEY_PREFIX + "username"; private static final String AUTH_TOKEN_TYPE = AccountContract.AUTH_TOKEN_TYPE_FRODO; @BindView(R.id.form) View mFormLayout; @BindView(R.id.username_layout) TextInputLayout mUsernameLayout; @BindView(R.id.username) EditText mUsernameEdit; @BindView(R.id.password_layout) TextInputLayout mPasswordLayout; @BindView(R.id.password) EditText mPasswordEdit; @BindView(R.id.sign_in) Button mSignInButton; @BindView(R.id.sign_up) Button mSignUpButton; @BindView(R.id.progress) ProgressBar mProgress; private AuthenticateRequest mAuthenticateRequest; @AuthMode private String mAuthMode; private String mExtraUsername; public static AuthenticatorFragment newInstance(String authMode, String username) { //noinspection deprecation AuthenticatorFragment fragment = new AuthenticatorFragment(); FragmentUtils.getArgumentsBuilder(fragment) .putString(EXTRA_AUTH_MODE, authMode) .putString(EXTRA_USERNAME, username); return fragment; } /** * @deprecated Use {@link #newInstance(String, String)} instead. */ public AuthenticatorFragment() {} @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //noinspection WrongConstant mAuthMode = getArguments().getString(EXTRA_AUTH_MODE); mExtraUsername = getArguments().getString(EXTRA_USERNAME); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.authenticator_fragment, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mAuthenticateRequest = AuthenticateRequest.attachTo(this); // TODO: Make the card slide in from bottom. updateViews(false); if (savedInstanceState == null && !TextUtils.isEmpty(mExtraUsername)) { mUsernameEdit.setText(mExtraUsername); } ViewUtils.hideTextInputLayoutErrorOnTextChange(mUsernameEdit, mUsernameLayout); ViewUtils.hideTextInputLayoutErrorOnTextChange(mPasswordEdit, mPasswordLayout); mPasswordEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_ACTION_UNSPECIFIED) { authenticate(); return true; } return false; } }); mSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { authenticate(); } }); mSignUpButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NotImplementedManager.signUp(getActivity()); } }); Activity activity = getActivity(); switch (mAuthMode) { case AUTH_MODE_NEW: activity.setTitle(R.string.auth_title_new); break; case AUTH_MODE_ADD: activity.setTitle(R.string.auth_title_add); break; case AUTH_MODE_UPDATE: activity.setTitle(R.string.auth_title_update); // See the source of setKeyListener(null), it just satisfies our need. mUsernameEdit.setKeyListener(null); mPasswordEdit.requestFocus(); break; case AUTH_MODE_CONFIRM: activity.setTitle(R.string.auth_title_confirm); mUsernameEdit.setKeyListener(null); mPasswordEdit.requestFocus(); break; default: throw new IllegalArgumentException(); } } private void authenticate() { // Store values at the time of login attempt. String username = mUsernameEdit.getText().toString(); String password = mPasswordEdit.getText().toString(); boolean cancel = false; View errorView = null; if (TextUtils.isEmpty(username)) { mUsernameLayout.setError(getString(R.string.auth_error_empty_username)); errorView = mUsernameEdit; cancel = true; } if (TextUtils.isEmpty(password)) { mPasswordLayout.setError(getString(R.string.auth_error_empty_password)); if (errorView == null) { errorView = mPasswordEdit; } cancel = true; } if (cancel) { errorView.requestFocus(); } else { mAuthenticateRequest.start(AUTH_TOKEN_TYPE, username, password); } } @Override public void onAuthenticateStarted(int requestCode) { // FIXME mUsernameLayout.setError(null); mPasswordLayout.setError(null); updateViews(true); } @Override public void onAuthenticateFinished(int requestCode) { // DISABLED: Do so only when failed, otherwise leave the progress bar running till we // finish. //updateSignInUpViews(true); } @Override public void onAuthenticateSuccess(int requestCode, AuthenticateRequest.RequestState requestState, AuthenticationResponse response) { Account account = new Account(requestState.username, AccountContract.ACCOUNT_TYPE); switch (mAuthMode) { case AUTH_MODE_NEW: AccountUtils.addAccountExplicitly(account, requestState.password); AccountUtils.setActiveAccount(account); break; case AUTH_MODE_ADD: AccountUtils.addAccountExplicitly(account, requestState.password); break; case AUTH_MODE_UPDATE: case AUTH_MODE_CONFIRM: AccountUtils.setPassword(account, requestState.password); break; } AccountUtils.setUserName(account, response.userName); AccountUtils.setUserId(account, response.userId); AccountUtils.setAuthToken(account, AUTH_TOKEN_TYPE, response.accessToken); AccountUtils.setRefreshToken(account, AUTH_TOKEN_TYPE, response.refreshToken); Intent intent; switch (mAuthMode) { case AUTH_MODE_NEW: case AUTH_MODE_ADD: case AUTH_MODE_UPDATE: intent = makeSuccessIntent(requestState.username); break; case AUTH_MODE_CONFIRM: intent = makeBooleanIntent(true); break; default: throw new IllegalArgumentException(); } AppCompatAccountAuthenticatorActivity activity = (AppCompatAccountAuthenticatorActivity) getActivity(); activity.setAccountAuthenticatorResult(intent.getExtras()); activity.setResult(Activity.RESULT_OK, intent); activity.finish(); } @Override public void onAuthenticateError(int requestCode, AuthenticateRequest.RequestState requestState, ApiError error) { updateViews(true); LogUtils.e(error.toString()); if (error.bodyJson != null && error.code != Codes.Custom.INVALID_ERROR_RESPONSE) { String errorString = getString(error.getErrorStringRes()); Activity activity = getActivity(); switch (error.code) { case Codes.Token.INVALID_APIKEY: case Codes.Token.APIKEY_IS_BLOCKED: case Codes.Token.INVALID_REQUEST_URI: case Codes.Token.INVALID_CREDENCIAL2: case Codes.Token.REQUIRED_PARAMETER_IS_MISSING: case Codes.Token.CLIENT_SECRET_MISMATCH: ToastUtils.show(errorString, activity); startActivity(AuthenticatorUtils.makeSetApiKeyIntent((activity))); break; case Codes.Token.USER_HAS_BLOCKED: case Codes.Token.USER_LOCKED: ToastUtils.show(errorString, activity); startActivity(AuthenticatorUtils.makeWebsiteIntent(activity)); break; case Codes.Token.NOT_TRIAL_USER: case Codes.Token.INVALID_USER: mUsernameLayout.setError(errorString); break; default: mPasswordLayout.setError(errorString); break; } } else if (error.response != null) { mPasswordLayout.setError(getString(R.string.auth_error_invalid_response)); } else { mPasswordLayout.setError(getString(R.string.auth_error_unknown)); } } private void updateViews(boolean animate) { boolean authenticating = mAuthenticateRequest.isRequesting(); mFormLayout.setEnabled(!authenticating); if (animate) { if (authenticating) { ViewUtils.fadeOutThenFadeIn(mFormLayout, mProgress, false); } else { ViewUtils.fadeOutThenFadeIn(mProgress, mFormLayout, false); } } else { ViewUtils.setVisibleOrInvisible(mFormLayout, !authenticating); ViewUtils.setVisibleOrInvisible(mProgress, authenticating); } } private Intent makeSuccessIntent(String accountName) { Intent intent = new Intent(); intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountContract.ACCOUNT_TYPE); return intent; } private Intent makeBooleanIntent(boolean result) { Intent intent = new Intent(); intent.putExtra(AccountManager.KEY_BOOLEAN_RESULT, result); return intent; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/ui/AuthenticatorFragment.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
2,281
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.app; import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.accounts.NetworkErrorException; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import me.zhanghai.android.douya.account.info.AccountContract; import me.zhanghai.android.douya.account.ui.AuthenticatorActivity; import me.zhanghai.android.douya.account.util.AccountUtils; import me.zhanghai.android.douya.account.util.AuthenticatorUtils; import me.zhanghai.android.douya.network.api.ApiContract.Response.Error.Codes; import me.zhanghai.android.douya.network.api.ApiError; import me.zhanghai.android.douya.network.api.ApiService; import me.zhanghai.android.douya.network.api.info.AuthenticationResponse; import me.zhanghai.android.douya.util.LogUtils; import me.zhanghai.android.douya.util.MoreTextUtils; public class Authenticator extends AbstractAccountAuthenticator { private Context mContext; public Authenticator(Context context) { super(context); mContext = context; } @Override public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { throw new UnsupportedOperationException(); } @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { return makeIntentBundle(AuthenticatorActivity.makeIntent(response, AccountUtils.hasAccount() ? AuthenticatorActivity.AUTH_MODE_ADD : AuthenticatorActivity.AUTH_MODE_NEW, mContext)); } @Override public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { return makeIntentBundle(AuthenticatorActivity.makeIntent(response, AuthenticatorActivity.AUTH_MODE_CONFIRM, account.name, mContext)); } @Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) { // Validate authTokenType. if (!MoreTextUtils.equalsAny(authTokenType, AccountContract.AUTH_TOKEN_TYPE_API_V2, AccountContract.AUTH_TOKEN_TYPE_FRODO)) { return makeErrorBundle(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "invalid authTokenType:" + authTokenType); } // NOTE: // Seems that System is not doing this checking for us, see: // path_to_url // // Peek authToken from AccountManager first, will return null if failed. String authToken = AccountUtils.peekAuthToken(account, authTokenType); if (TextUtils.isEmpty(authToken)) { String refreshToken = AccountUtils.getRefreshToken(account, authTokenType); if (!TextUtils.isEmpty(refreshToken)) { try { AuthenticationResponse authenticationResponse = ApiService.getInstance() .authenticate(authTokenType, refreshToken).execute(); authToken = authenticationResponse.accessToken; AccountUtils.setUserName(account, authenticationResponse.userName); AccountUtils.setUserId(account, authenticationResponse.userId); AccountUtils.setRefreshToken(account, authTokenType, authenticationResponse.refreshToken); } catch (ApiError e) { LogUtils.e(e.toString()); // Try again with XAuth afterwards. } } } if (TextUtils.isEmpty(authToken)) { String password = AccountUtils.getPassword(account); if (password == null) { return makeErrorBundle(AccountManager.ERROR_CODE_BAD_AUTHENTICATION, "AccountManager.getPassword() returned null"); } ApiService apiService = ApiService.getInstance(); try { AuthenticationResponse authenticationResponse = apiService.authenticate( authTokenType, account.name, password).execute(); authToken = authenticationResponse.accessToken; AccountUtils.setUserName(account, authenticationResponse.userName); AccountUtils.setUserId(account, authenticationResponse.userId); AccountUtils.setRefreshToken(account, authTokenType, authenticationResponse.refreshToken); } catch (ApiError e) { LogUtils.e(e.toString()); if (e.bodyJson != null && e.code != Codes.Custom.INVALID_ERROR_RESPONSE) { String errorString = ApiError.getErrorString(e, mContext); switch (e.code) { case Codes.Token.INVALID_APIKEY: case Codes.Token.APIKEY_IS_BLOCKED: case Codes.Token.INVALID_REQUEST_URI: case Codes.Token.INVALID_CREDENCIAL2: case Codes.Token.REQUIRED_PARAMETER_IS_MISSING: case Codes.Token.CLIENT_SECRET_MISMATCH: ApiService.getInstance().cancelApiRequests(); return makeFailureIntentBundle( AuthenticatorUtils.makeSetApiKeyIntent(mContext), errorString); case Codes.Token.USERNAME_PASSWORD_MISMATCH: ApiService.getInstance().cancelApiRequests(); return makeFailureIntentBundle(makeUpdateCredentialIntent(response, account), errorString); case Codes.Token.INVALID_USER: case Codes.Token.USER_HAS_BLOCKED: case Codes.Token.USER_LOCKED: ApiService.getInstance().cancelApiRequests(); return makeFailureIntentBundle( AuthenticatorUtils.makeWebsiteIntent(mContext), errorString); } return makeErrorBundle(AccountManager.ERROR_CODE_BAD_AUTHENTICATION, errorString); } else if (e.response != null) { return makeErrorBundle(AccountManager.ERROR_CODE_INVALID_RESPONSE, e); } else { return makeErrorBundle(AccountManager.ERROR_CODE_NETWORK_ERROR, e); } } } if (TextUtils.isEmpty(authToken)) { // Should not happen, the only case should be when TokenRequest.Response.accessToken is // null. return makeErrorBundle(AccountManager.ERROR_CODE_INVALID_RESPONSE, "authToken is still null"); } // Return the result. Bundle result = makeSuccessBundle(account.name); result.putString(AccountManager.KEY_AUTHTOKEN, authToken); return result; } @Override public String getAuthTokenLabel(String authTokenType) { // NOTE: // null means we don't support multiple authToken types, according to the example // SampleSyncAdapter. return null; } @Override public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { return makeIntentBundle(makeUpdateCredentialIntent(response, account)); } @Override public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException { return null; } private Intent makeUpdateCredentialIntent(AccountAuthenticatorResponse response, Account account) { return AuthenticatorActivity.makeIntent(response, AuthenticatorActivity.AUTH_MODE_UPDATE, account.name, mContext); } private Bundle makeIntentBundle(Intent intent) { Bundle bundle = new Bundle(); bundle.putParcelable(AccountManager.KEY_INTENT, intent); return bundle; } private Bundle makeFailureIntentBundle(Intent intent, String authFailedMessage) { Bundle bundle = makeIntentBundle(intent); bundle.putString(AccountManager.KEY_AUTH_FAILED_MESSAGE, authFailedMessage); return bundle; } private Bundle makeErrorBundle(int errorCode, String errorMessage) { Bundle bundle = new Bundle(); bundle.putInt(AccountManager.KEY_ERROR_CODE, errorCode); bundle.putString(AccountManager.KEY_ERROR_MESSAGE, errorMessage); return bundle; } private Bundle makeErrorBundle(int errorCode, Throwable throwable) { return makeErrorBundle(errorCode, throwable.toString()); } private Bundle makeSuccessBundle(String accountName) { Bundle bundle = new Bundle(); bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accountName); bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, AccountContract.ACCOUNT_TYPE); return bundle; } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/app/Authenticator.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,568
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.app; import android.accounts.Account; import android.accounts.AccountManager; import android.content.SharedPreferences; import android.os.Handler; import android.os.Looper; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import me.zhanghai.android.douya.account.util.AccountUtils; import me.zhanghai.android.douya.util.IoUtils; /** * An {@link Account} based {@link SharedPreferences} implementation using * {@link AccountManager#getUserData(Account, String)} and * {@link AccountManager#setUserData(Account, String, String)}. * * <p>Due to the limitation of {@link AccountManager}, we can only access a value by its key, but we * cannot access the key set or the entire map. So {@link #getAll()} and {@link #clear()} are * unsupported, {@link #edit()}, {@link #commit()} and {@link #apply()} are stub, and changes are * committed immediately.</p> * * <p>Also due to the limitation of {@link AccountManager}, all values are stored as {@link String}, * so {@link #putStringSet(String, Set)} needs to flatten the {@link String} array into one * {@link String}, in this case the character bar ('|') is used as the delimiter.</p> * * @see SharedPreferences * @see AccountManager */ public class AccountPreferences implements SharedPreferences, SharedPreferences.Editor { private static final String TRUE_STRING = "true"; private static final String FALSE_STRING = "false"; private static final Object INSTANCES_LOCK = new Object(); // NOTE: Not using WeakHashMap and WeakReference for instance map because we don't won't to // lose registered listeners. private static final Map<Account, AccountPreferences> INSTANCES = new HashMap<>(); private AccountManager mAccountManager = AccountUtils.getAccountManager(); private Account mAccount; private Handler mainHandler = new Handler(Looper.getMainLooper()); private Set<OnSharedPreferenceChangeListener> listeners = Collections.newSetFromMap( new WeakHashMap<OnSharedPreferenceChangeListener, Boolean>()); private AccountPreferences(Account account) { mAccount = account; } public static AccountPreferences forAccount(Account account) { if (account == null) { throw new IllegalArgumentException("account is null"); } synchronized (INSTANCES_LOCK) { AccountPreferences accountPreferences = INSTANCES.get(account); if (accountPreferences == null) { accountPreferences = new AccountPreferences(account); INSTANCES.put(account, accountPreferences); } return accountPreferences; } } /** * {@inheritDoc} */ @Override public String getString(String key, String defaultValue) { String value = mAccountManager.getUserData(mAccount, key); return value != null ? value : defaultValue; } /** * {@inheritDoc} */ @Override public Set<String> getStringSet(String key, Set<String> defaultValue) { String stringValue = getString(key, null); if (stringValue == null) { return defaultValue; } else { Set<String> value = new HashSet<>(); Collections.addAll(value, IoUtils.stringToStringArray(stringValue)); return value; } } /** * {@inheritDoc} */ @Override public int getInt(String key, int defaultValue) { String stringValue = getString(key, null); if (stringValue == null) { return defaultValue; } else { try { return Integer.parseInt(stringValue); } catch (NumberFormatException e) { e.printStackTrace(); return defaultValue; } } } /** * {@inheritDoc} */ @Override public long getLong(String key, long defaultValue) { String stringValue = getString(key, null); if (stringValue == null) { return defaultValue; } else { try { return Long.parseLong(stringValue); } catch (NumberFormatException e) { e.printStackTrace(); return defaultValue; } } } /** * {@inheritDoc} */ @Override public float getFloat(String key, float defaultValue) { String stringValue = getString(key, null); if (stringValue == null) { return defaultValue; } else { try { return Float.parseFloat(stringValue); } catch (NumberFormatException e) { e.printStackTrace(); return defaultValue; } } } /** * {@inheritDoc} */ @Override public boolean getBoolean(String key, boolean defaultValue) { String stringValue = getString(key, null); if (stringValue == null) { return defaultValue; } else { switch (stringValue) { case TRUE_STRING: return true; case FALSE_STRING: return false; default: return defaultValue; } } } /** * Unsupported operation. * * Due to the limitation of {@link AccountManager}, we can only access a value by its key, but we * cannot access the key set or the entire map.. Calling this method will throw an * {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException */ @Override public Map<String, ?> getAll() { throw new UnsupportedOperationException("getAll() is not supported by AccountManager"); } /** * {@inheritDoc} */ @Override public boolean contains(String key) { return getString(key, null) != null; } /** * Stub method. * * Due to the limitation of {@link AccountManager}, we cannot batch commit changes, so this * instance itself is returned. * * @return Returns this instance. */ @Override public Editor edit() { return this; } /** * {@inheritDoc} */ @Override public AccountPreferences putString(String key, String value) { mAccountManager.setUserData(mAccount, key, value); notifyChanged(key); return this; } /** * {@inheritDoc} * * <p>Due to the limitation of {@link AccountManager}, all values are stored as {@link String}, * so {@link #putStringSet(String, Set)} needs to flatten the {@link String} array into one * {@link String}, in this case the character bar ('|') is used as the delimiter.</p> */ @Override public AccountPreferences putStringSet(String key, Set<String> value) { return putString(key, value != null ? IoUtils.collectionToString(value) : null); } /** * {@inheritDoc} */ @Override public AccountPreferences putInt(String key, int value) { return putString(key, Integer.toString(value)); } /** * {@inheritDoc} */ @Override public AccountPreferences putLong(String key, long value) { return putString(key, Long.toString(value)); } /** * {@inheritDoc} */ @Override public AccountPreferences putFloat(String key, float value) { return putString(key, Float.toString(value)); } /** * {@inheritDoc} */ @Override public AccountPreferences putBoolean(String key, boolean value) { return putString(key, value ? TRUE_STRING : FALSE_STRING); } /** * {@inheritDoc} */ @Override public AccountPreferences remove(String key) { return putString(key, null); } /** * Unsupported operation. * * Due to the limitation of {@link AccountManager}, we can only access a value by its key, but we * cannot access the key set or the entire map. Calling this method will throw an * {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException */ @Override public Editor clear() { throw new UnsupportedOperationException("clear() is not supported by AccountManager"); } /** * Stub method. * * Due to the limitation of {@link AccountManager}, we cannot batch commit changes, so nothing * is done and it will always success. * * @return Always returns true. */ @Override public boolean commit() { return true; } /** * Stub method. * * Due to the limitation of {@link AccountManager}, we cannot batch commit changes, so nothing * is done. */ @Override public void apply() {} /** * {@inheritDoc} */ @Override public void registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { listeners.add(listener); } /** * {@inheritDoc} */ @Override public void unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { listeners.remove(listener); } private void notifyChanged(final String key) { if (Looper.myLooper() == Looper.getMainLooper()) { for (OnSharedPreferenceChangeListener listener : listeners) { if (listener != null) { listener.onSharedPreferenceChanged(AccountPreferences.this, key); } } } else { mainHandler.post(new Runnable() { @Override public void run() { notifyChanged(key); } }); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/app/AccountPreferences.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,978
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.util; import android.content.Context; import android.content.Intent; import android.net.Uri; import me.zhanghai.android.douya.ui.WebViewActivity; public class AuthenticatorUtils { private AuthenticatorUtils() {} public static Intent makeSetApiKeyIntent(Context context) { // Implicit intent with ACTION_VIEW is not launched by account manager. return WebViewActivity.makeIntent(Uri.parse( "path_to_url"), context); } public static Intent makeWebsiteIntent(Context context) { // Implicit intent with ACTION_VIEW is not launched by account manager. return WebViewActivity.makeIntent(Uri.parse("path_to_url"), context); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/util/AuthenticatorUtils.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
150
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.content; import android.accounts.Account; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import me.zhanghai.android.douya.account.util.AccountUtils; import me.zhanghai.android.douya.network.api.info.apiv2.SimpleUser; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.user.content.UserResource; import me.zhanghai.android.douya.util.FragmentUtils; public class AccountUserResource extends UserResource { private static final String KEY_PREFIX = AccountUserResource.class.getName() + '.'; private final String EXTRA_ACCOUNT = KEY_PREFIX + "account"; private Account mAccount; private static final String FRAGMENT_TAG_DEFAULT = AccountUserResource.class.getName(); private static AccountUserResource newInstance(Account account) { //noinspection deprecation return new AccountUserResource().setArguments(account); } public static AccountUserResource attachTo(Account account, Fragment fragment, String tag, int requestCode) { FragmentActivity activity = fragment.getActivity(); AccountUserResource instance = FragmentUtils.findByTag(activity, tag); if (instance == null) { instance = newInstance(account); FragmentUtils.add(instance, activity, tag); } instance.setTarget(fragment, requestCode); return instance; } public static AccountUserResource attachTo(Account account, Fragment fragment) { return attachTo(account, fragment, FRAGMENT_TAG_DEFAULT, REQUEST_CODE_INVALID); } /** * @deprecated Use {@code attachTo()} instead. */ @SuppressWarnings("deprecation") public AccountUserResource() {} protected AccountUserResource setArguments(Account account) { SimpleUser partialUser = makePartialUser(account); super.setArguments(partialUser.getIdOrUid(), partialUser, AccountUtils.getUser(account)); FragmentUtils.getArgumentsBuilder(this) .putParcelable(EXTRA_ACCOUNT, account); return this; } private SimpleUser makePartialUser(Account account) { SimpleUser partialUser = new SimpleUser(); //noinspection deprecation partialUser.id = AccountUtils.getUserId(account); //noinspection deprecation partialUser.uid = String.valueOf(partialUser.id); partialUser.name = AccountUtils.getUserName(account); return partialUser; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAccount = getArguments().getParcelable(EXTRA_ACCOUNT); } @Override protected void loadOnStart() { // Always load, so that we can ever get refreshed. onLoadOnStart(); } @Override protected void onLoadSuccess(User user) { super.onLoadSuccess(user); AccountUtils.setUserName(mAccount, user.name); AccountUtils.setUser(mAccount, user); } @Deprecated @Override public boolean hasSimpleUser() { throw new IllegalStateException("We always have a (partial) user"); } @Deprecated @Override public SimpleUser getSimpleUser() { throw new IllegalStateException("Use getPartialUser() instead"); } public SimpleUser getPartialUser() { return super.getSimpleUser(); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/content/AccountUserResource.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
682
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.content; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import me.zhanghai.android.douya.network.RequestFragment; import me.zhanghai.android.douya.network.api.ApiRequest; import me.zhanghai.android.douya.network.api.ApiError; import me.zhanghai.android.douya.network.api.ApiService; import me.zhanghai.android.douya.network.api.info.AuthenticationResponse; import me.zhanghai.android.douya.util.FragmentUtils; public class AuthenticateRequest extends RequestFragment<AuthenticateRequest.RequestState, AuthenticationResponse> { private static final String FRAGMENT_TAG_DEFAULT = AuthenticateRequest.class.getName(); public static AuthenticateRequest attachTo(Fragment fragment, String tag, int requestCode) { FragmentActivity activity = fragment.getActivity(); AuthenticateRequest instance = FragmentUtils.findByTag(activity, tag); if (instance == null) { //noinspection deprecation instance = new AuthenticateRequest(); FragmentUtils.add(instance, activity, tag); } instance.setTarget(fragment, requestCode); return instance; } public static AuthenticateRequest attachTo(Fragment fragment) { return attachTo(fragment, FRAGMENT_TAG_DEFAULT, REQUEST_CODE_INVALID); } /** * @deprecated Use {@code attachTo()} instead. */ public AuthenticateRequest() {} public void start(String authTokenType, String username, String password) { start(new RequestState(authTokenType, username, password)); } @Override protected ApiRequest<AuthenticationResponse> onCreateRequest(RequestState requestState) { return ApiService.getInstance().authenticate(requestState.authTokenType, requestState.username, requestState.password); } @Override protected void onRequestStarted() { getListener().onAuthenticateStarted(getRequestCode()); } @Override protected void onRequestFinished(boolean successful, RequestState requestState, AuthenticationResponse response, ApiError error) { getListener().onAuthenticateFinished(getRequestCode()); if (successful) { getListener().onAuthenticateSuccess(getRequestCode(), requestState, response); } else { getListener().onAuthenticateError(getRequestCode(), requestState, error); } } private Listener getListener() { return (Listener) getTarget(); } public static class RequestState { public String authTokenType; public String username; public String password; public RequestState(String authTokenType, String username, String password) { this.authTokenType = authTokenType; this.username = username; this.password = password; } } public interface Listener { void onAuthenticateStarted(int requestCode); void onAuthenticateFinished(int requestCode); void onAuthenticateSuccess(int requestCode, RequestState requestState, AuthenticationResponse response); void onAuthenticateError(int requestCode, RequestState requestState, ApiError error); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/content/AuthenticateRequest.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
603
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.account.util; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OnAccountsUpdateListener; import android.accounts.OperationCanceledException; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import com.google.gson.JsonParseException; import java.io.IOException; import me.zhanghai.android.douya.DouyaApplication; import me.zhanghai.android.douya.account.app.AccountPreferences; import me.zhanghai.android.douya.account.info.AccountContract; import me.zhanghai.android.douya.account.ui.AddAccountActivity; import me.zhanghai.android.douya.account.ui.SelectAccountActivity; import me.zhanghai.android.douya.network.api.ApiAuthenticators; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.settings.info.Settings; import me.zhanghai.android.douya.util.GsonHelper; public class AccountUtils { public static AccountManager getAccountManager() { return AccountManager.get(DouyaApplication.getInstance()); } public static AccountManagerFuture<Bundle> addAccount(Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) { return getAccountManager().addAccount(AccountContract.ACCOUNT_TYPE, AccountContract.AUTH_TOKEN_TYPE_FRODO, null, null, activity, callback, handler); } public static AccountManagerFuture<Bundle> addAccount(Activity activity) { return addAccount(activity, null, null); } public static void addAccount(Activity activity, Intent onAddedIntent) { activity.startActivity(AddAccountActivity.makeIntent(onAddedIntent, activity)); } public static boolean addAccountExplicitly(Account account, String password) { return getAccountManager().addAccountExplicitly(account, password, null); } public static AccountManagerFuture<Bundle> updatePassword(Activity activity, Account account, AccountManagerCallback<Bundle> callback, Handler handler) { return getAccountManager().updateCredentials(account, AccountContract.AUTH_TOKEN_TYPE_FRODO, null, activity, callback, handler); } public static AccountManagerFuture<Bundle> updatePassword(Activity activity, Account account) { return updatePassword(activity, account, null, null); } public static AccountManagerFuture<Bundle> confirmPassword( Activity activity, Account account, AccountManagerCallback<Bundle> callback, Handler handler) { return getAccountManager().confirmCredentials(account, null, activity, callback, handler); } public interface ConfirmPasswordListener { void onConfirmed(); void onFailed(); } private static AccountManagerCallback<Bundle> makeConfirmPasswordCallback( ConfirmPasswordListener listener) { return future -> { try { boolean confirmed = future.getResult() .getBoolean(AccountManager.KEY_BOOLEAN_RESULT); if (confirmed) { listener.onConfirmed(); } else { listener.onFailed(); } } catch (AuthenticatorException | IOException | OperationCanceledException e) { e.printStackTrace(); listener.onFailed(); } }; } public static void confirmPassword(Activity activity, Account account, ConfirmPasswordListener listener, Handler handler) { confirmPassword(activity, account, makeConfirmPasswordCallback(listener), handler); } public static void confirmPassword(Activity activity, ConfirmPasswordListener listener) { confirmPassword(activity, getActiveAccount(), listener, null); } // REMOVEME: This seems infeasible. And we should check against local password instead of using // network public static Intent makeConfirmPasswordIntent(Account account, ConfirmPasswordListener listener) { try { return confirmPassword(null, account, makeConfirmPasswordCallback(listener), null) .getResult().getParcelable(AccountManager.KEY_INTENT); } catch (AuthenticatorException | IOException | OperationCanceledException e) { e.printStackTrace(); return null; } } public static Intent makeConfirmPasswordIntent(ConfirmPasswordListener listener) { return makeConfirmPasswordIntent(getActiveAccount(), listener); } public static void addOnAccountListUpdatedListener(OnAccountsUpdateListener listener) { getAccountManager().addOnAccountsUpdatedListener(listener, null, false); } public static void removeOnAccountListUpdatedListener(OnAccountsUpdateListener listener) { getAccountManager().removeOnAccountsUpdatedListener(listener); } public static Account[] getAccounts() { return getAccountManager().getAccountsByType(AccountContract.ACCOUNT_TYPE); } private static Account getAccountByName(String accountName) { if (TextUtils.isEmpty(accountName)) { return null; } for (Account account : getAccounts()) { if (TextUtils.equals(account.name, accountName)) { return account; } } return null; } // NOTE: This method is asynchronous. public static void removeAccount(Account account) { //noinspection deprecation getAccountManager().removeAccount(account, null, null); } public static boolean hasAccount() { return getAccounts().length != 0; } // NOTE: Use getActiveAccount() instead for availability checking. private static String getActiveAccountName() { return Settings.ACTIVE_ACCOUNT_NAME.getValue(); } private static void setActiveAccountName(String accountName) { Settings.ACTIVE_ACCOUNT_NAME.putValue(accountName); } private static void removeActiveAccountName() { Settings.ACTIVE_ACCOUNT_NAME.remove(); } public static boolean hasActiveAccountName() { return !TextUtils.isEmpty(getActiveAccountName()); } public static boolean isActiveAccountName(String accountName) { return TextUtils.equals(accountName, getActiveAccountName()); } // NOTICE: // Will clear the invalid setting and return null if no matching account with the name from // setting is found. public static Account getActiveAccount() { Account account = getAccountByName(getActiveAccountName()); if (account != null) { return account; } else { removeActiveAccountName(); return null; } } public static void setActiveAccount(Account account) { if (account == null) { removeActiveAccountName(); return; } Account oldActiveAccount = getActiveAccount(); setActiveAccountName(account.name); if (oldActiveAccount != null) { if (TextUtils.equals(getRecentOneAccountName(), account.name)) { setRecentOneAccountName(oldActiveAccount.name); } else if (TextUtils.equals(getRecentTwoAccountName(), account.name)) { setRecentTwoAccountName(oldActiveAccount.name); } else { setRecentTwoAccountName(getRecentOneAccountName()); setRecentOneAccountName(oldActiveAccount.name); } } ApiAuthenticators.getInstance().notifyActiveAccountChanged(); } public static boolean hasActiveAccount() { return getActiveAccount() != null; } public static boolean isActiveAccount(Account account) { return isActiveAccountName(account.name); } private static String getRecentOneAccountName() { return Settings.RECENT_ONE_ACCOUNT_NAME.getValue(); } private static void setRecentOneAccountName(String accountName) { Settings.RECENT_ONE_ACCOUNT_NAME.putValue(accountName); } private static void removeRecentOneAccountName() { Settings.RECENT_ONE_ACCOUNT_NAME.remove(); } public static Account getRecentOneAccount() { Account activeAccount = getActiveAccount(); if (activeAccount == null) { return null; } String accountName = getRecentOneAccountName(); if (!TextUtils.isEmpty(accountName) && !TextUtils.equals(accountName, activeAccount.name)) { Account account = getAccountByName(accountName); if (account != null) { return account; } } for (Account account : getAccounts()) { if (!account.equals(activeAccount)) { setRecentOneAccountName(account.name); return account; } } removeRecentOneAccountName(); return null; } private static String getRecentTwoAccountName() { return Settings.RECENT_TWO_ACCOUNT_NAME.getValue(); } private static void setRecentTwoAccountName(String accountName) { Settings.RECENT_TWO_ACCOUNT_NAME.putValue(accountName); } private static void removeRecentTwoAccountName() { Settings.RECENT_TWO_ACCOUNT_NAME.remove(); } public static Account getRecentTwoAccount() { Account activeAccount = getActiveAccount(); if (activeAccount == null) { return null; } Account recentOneAccount = getRecentOneAccount(); if (recentOneAccount == null) { return null; } String accountName = getRecentTwoAccountName(); if (!TextUtils.isEmpty(accountName) && !TextUtils.equals(accountName, activeAccount.name) && !TextUtils.equals(accountName, recentOneAccount.name)) { Account account = getAccountByName(accountName); if (account != null) { return account; } } for (Account account : getAccounts()) { if (!account.equals(activeAccount) && !account.equals(recentOneAccount)) { setRecentTwoAccountName(account.name); return account; } } removeRecentTwoAccountName(); return null; } // NOTICE: Be sure to check hasAccount() before calling this. // NOTE: // Only intended for selecting an active account when there is none, changing active // account should be handled in settings. public static void selectAccount(Activity activity, Intent onSelectedIntent) { if (getAccounts().length == 0) { throw new IllegalStateException("Should have checked for hasAccount()"); } activity.startActivity(SelectAccountActivity.makeIntent(onSelectedIntent, activity)); } public static boolean ensureActiveAccountAvailability(Activity activity) { boolean accountAvailable = true; if (!hasAccount()) { accountAvailable = false; addAccount(activity, activity.getIntent()); } else if (!hasActiveAccount()) { accountAvailable = false; selectAccount(activity, activity.getIntent()); } if (!accountAvailable) { activity.finish(); } return accountAvailable; } public static String getPassword(Account account) { return getAccountManager().getPassword(account); } public static void setPassword(Account account, String password) { getAccountManager().setPassword(account, password); } public static String peekAuthToken(Account account, String type) { return getAccountManager().peekAuthToken(account, type); } public static void getAuthToken(Account account, String type, AccountManagerCallback<Bundle> callback, Handler handler) { getAccountManager().getAuthToken(account, type, null, true, callback, handler); } public interface GetAuthTokenListener { void onResult(String authToken); void onFailed(); } private static AccountManagerCallback<Bundle> makeGetAuthTokenCallback( GetAuthTokenListener listener) { return future -> { try { String authToken = future.getResult() .getString(AccountManager.KEY_AUTHTOKEN); if (!TextUtils.isEmpty(authToken)) { listener.onResult(authToken); } else { listener.onFailed(); } } catch (AuthenticatorException | IOException | OperationCanceledException e) { e.printStackTrace(); listener.onFailed(); } }; } public static void getAuthToken(Account account, String type, GetAuthTokenListener listener, Handler handler) { getAuthToken(account, type, makeGetAuthTokenCallback(listener), handler); } public static void getAuthToken(Account account, String type, GetAuthTokenListener listener) { getAuthToken(account, type, listener, null); } public static void setAuthToken(Account account, String type, String authToken) { getAccountManager().setAuthToken(account, type, authToken); } public static void invalidateAuthToken(String authToken) { getAccountManager().invalidateAuthToken(AccountContract.ACCOUNT_TYPE, authToken); } // User name is different from username: user name is the display name in User.name, but // username is the account name for logging in. public static String getUserName(Account account) { return AccountPreferences.forAccount(account).getString(AccountContract.KEY_USER_NAME, null); } public static String getUserName() { return getUserName(getActiveAccount()); } public static void setUserName(Account account, String userName) { AccountPreferences.forAccount(account).putString(AccountContract.KEY_USER_NAME, userName); } public static long getUserId(Account account) { return AccountPreferences.forAccount(account).getLong(AccountContract.KEY_USER_ID, AccountContract.INVALID_USER_ID); } public static long getUserId() { return getUserId(getActiveAccount()); } public static void setUserId(Account account, long userId) { AccountPreferences.forAccount(account).putLong(AccountContract.KEY_USER_ID, userId); } public static String getRefreshToken(Account account, String authTokenType) { return AccountPreferences.forAccount(account).getString(getRefreshTokenKey(authTokenType), null); } public static void setRefreshToken(Account account, String authTokenType, String refreshToken) { AccountPreferences.forAccount(account).putString(getRefreshTokenKey(authTokenType), refreshToken); } private static String getRefreshTokenKey(String authTokenType) { switch (authTokenType) { case AccountContract.AUTH_TOKEN_TYPE_API_V2: return AccountContract.KEY_REFRESH_TOKEN_API_V2; case AccountContract.AUTH_TOKEN_TYPE_FRODO: return AccountContract.KEY_REFRESH_TOKEN_FRODO; default: throw new IllegalArgumentException("Unknown authTokenType: " + authTokenType); } } public static User getUser(Account account) { String userInfoJson = AccountPreferences.forAccount(account).getString( AccountContract.KEY_USER_INFO, null); if (!TextUtils.isEmpty(userInfoJson)) { try { return GsonHelper.GSON.fromJson(userInfoJson, User.class); } catch (JsonParseException e) { e.printStackTrace(); } } return null; } public static void setUser(Account account, User user) { String userInfoJson = GsonHelper.GSON.toJson(user, User.class); AccountPreferences.forAccount(account).putString(AccountContract.KEY_USER_INFO, userInfoJson); } public static User getUser() { return getUser(getActiveAccount()); } public static void setUser(User user) { setUser(getActiveAccount(), user); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/account/util/AccountUtils.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
3,057
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatDialogFragment; import me.zhanghai.android.douya.R; public class ConfirmUnfollowUserDialogFragment extends AppCompatDialogFragment { /** * @deprecated Use {@link #newInstance()} instead. */ public ConfirmUnfollowUserDialogFragment() {} public static ConfirmUnfollowUserDialogFragment newInstance() { //noinspection deprecation return new ConfirmUnfollowUserDialogFragment(); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity(), getTheme()) .setMessage(R.string.user_unfollow_confirm) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { getListener().onUnfollowUser(); } }) .setNegativeButton(R.string.cancel, null) .create(); } private Listener getListener() { return (Listener) getParentFragment(); } public static void show(Fragment fragment) { ConfirmUnfollowUserDialogFragment.newInstance() .show(fragment.getChildFragmentManager(), null); } public interface Listener { void onUnfollowUser(); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ConfirmUnfollowUserDialogFragment.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
298
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.link.UriHandler; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.network.api.info.frodo.SimpleReview; import me.zhanghai.android.douya.ui.FriendlyCardView; import me.zhanghai.android.douya.util.ImageUtils; import me.zhanghai.android.douya.util.StringUtils; import me.zhanghai.android.douya.util.ViewUtils; public class ProfileReviewsLayout extends FriendlyCardView { private static final int REVIEW_COUNT_MAX = 3; @BindView(R.id.title) TextView mTitleText; @BindView(R.id.review_list) LinearLayout mReviewList; @BindView(R.id.empty) View mEmptyView; @BindView(R.id.view_more) TextView mViewMoreText; public ProfileReviewsLayout(Context context) { super(context); init(); } public ProfileReviewsLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ProfileReviewsLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { ViewUtils.inflateInto(R.layout.profile_reviews_layout, this); ButterKnife.bind(this); } public void bind(final User user, List<SimpleReview> reviewList) { final Context context = getContext(); OnClickListener viewMoreListener = new OnClickListener() { @Override public void onClick(View view) { // TODO UriHandler.open(StringUtils.formatUs("path_to_url", user.getIdOrUid()), context); //context.startActivity(ReviewListActivity.makeIntent(mUser, context)); } }; mTitleText.setOnClickListener(viewMoreListener); mViewMoreText.setOnClickListener(viewMoreListener); int i = 0; for (final SimpleReview review : reviewList) { if (i >= REVIEW_COUNT_MAX) { break; } if (i >= mReviewList.getChildCount()) { LayoutInflater.from(context) .inflate(R.layout.profile_review_item, mReviewList); } View reviewLayout = mReviewList.getChildAt(i); ReviewLayoutHolder holder = (ReviewLayoutHolder) reviewLayout.getTag(); if (holder == null) { holder = new ReviewLayoutHolder(reviewLayout); reviewLayout.setTag(holder); ViewUtils.setTextViewLinkClickable(holder.titleText); } String coverUrl = review.coverUrl; if (TextUtils.isEmpty(coverUrl) && review.item != null && review.item.cover != null) { coverUrl = review.item.cover.getMediumUrl(); } if (!TextUtils.isEmpty(coverUrl)) { holder.coverImage.setVisibility(VISIBLE); ImageUtils.loadImage(holder.coverImage, coverUrl); } else { holder.coverImage.setVisibility(GONE); } holder.titleText.setText(review.title); holder.abstractText.setText(review.abstract_); reviewLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // TODO UriHandler.open(StringUtils.formatUs("path_to_url", review.id), context); //context.startActivity(ReviewActivity.makeIntent(review, context)); } }); ++i; } ViewUtils.setVisibleOrGone(mReviewList, i != 0); ViewUtils.setVisibleOrGone(mEmptyView, i == 0); // HACK: We don't have mUser.reviewCount, but normally we request more than // REVIEW_COUNT_MAX. // FIXME: Fix this hack? //if (mUser.reviewCount > i) { if (reviewList.size() > i) { mViewMoreText.setText(R.string.view_more); } else { mViewMoreText.setVisibility(GONE); } for (int count = mReviewList.getChildCount(); i < count; ++i) { ViewUtils.setVisibleOrGone(mReviewList.getChildAt(i), false); } } static class ReviewLayoutHolder { @BindView(R.id.cover) public ImageView coverImage; @BindView(R.id.title) public TextView titleText; @BindView(R.id.abstract_) public TextView abstractText; public ReviewLayoutHolder(View reviewLayout) { ButterKnife.bind(this, reviewLayout); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileReviewsLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
983
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.broadcast.ui.BroadcastActivity; import me.zhanghai.android.douya.broadcast.ui.BroadcastListActivity; import me.zhanghai.android.douya.network.api.info.frodo.Broadcast; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.ui.FriendlyCardView; import me.zhanghai.android.douya.ui.SizedImageItem; import me.zhanghai.android.douya.ui.TimeTextView; import me.zhanghai.android.douya.util.ImageUtils; import me.zhanghai.android.douya.util.ViewUtils; public class ProfileBroadcastsLayout extends FriendlyCardView { private static final int BROADCAST_COUNT_MAX = 3; @BindView(R.id.title) TextView mTitleText; @BindView(R.id.broadcast_list) LinearLayout mBroadcastList; @BindView(R.id.empty) View mEmptyView; @BindView(R.id.view_more) TextView mViewMoreText; public ProfileBroadcastsLayout(Context context) { super(context); init(); } public ProfileBroadcastsLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ProfileBroadcastsLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { ViewUtils.inflateInto(R.layout.profile_broadcasts_layout, this); ButterKnife.bind(this); } public void bind(User user, List<Broadcast> broadcastList) { Context context = getContext(); View.OnClickListener viewMoreListener = view -> context.startActivity( BroadcastListActivity.makeIntent(user, context)); mTitleText.setOnClickListener(viewMoreListener); mViewMoreText.setOnClickListener(viewMoreListener); int i = 0; for (Broadcast broadcast : broadcastList) { if (i >= BROADCAST_COUNT_MAX) { break; } if (broadcast.rebroadcastedBroadcast != null) { continue; } if (i >= mBroadcastList.getChildCount()) { ViewUtils.inflateInto(R.layout.profile_broadcast_item, mBroadcastList); } View broadcastLayout = mBroadcastList.getChildAt(i); broadcastLayout.setVisibility(VISIBLE); BroadcastLayoutHolder holder = (BroadcastLayoutHolder) broadcastLayout.getTag(); if (holder == null) { holder = new BroadcastLayoutHolder(broadcastLayout); broadcastLayout.setTag(holder); ViewUtils.setTextViewLinkClickable(holder.textText); } // HACK: Should not change on rebind. if (holder.boundBroadcastId != broadcast.id) { SizedImageItem image = null; if (broadcast.attachment != null) { image = broadcast.attachment.image; } if (image == null) { List<? extends SizedImageItem> images = broadcast.attachment != null && broadcast.attachment.imageList != null ? broadcast.attachment.imageList.images : broadcast.images; if (images.size() > 0){ image = images.get(0); } } if (image != null) { holder.image.setVisibility(VISIBLE); ImageUtils.loadImage(holder.image, image); } else { holder.image.setVisibility(GONE); } CharSequence text = broadcast.getTextWithEntities(context); if (TextUtils.isEmpty(text) && broadcast.attachment != null) { text = broadcast.attachment.title; } holder.textText.setText(text); boolean hasTime = !TextUtils.isEmpty(broadcast.createTime); ViewUtils.setVisibleOrGone(holder.timeText, hasTime); if (hasTime) { holder.timeText.setDoubanTime(broadcast.createTime); } ViewUtils.setVisibleOrGone(holder.timeActionSpace, hasTime); holder.actionText.setText(broadcast.action); broadcastLayout.setOnClickListener(view -> context.startActivity( BroadcastActivity.makeIntent(broadcast, context))); holder.boundBroadcastId = broadcast.id; } ++i; } ViewUtils.setVisibleOrGone(mBroadcastList, i != 0); ViewUtils.setVisibleOrGone(mEmptyView, i == 0); if (user.broadcastCount > i) { mViewMoreText.setText(context.getString(R.string.view_more_with_count_format, user.broadcastCount)); } else { mViewMoreText.setVisibility(GONE); } for (int count = mBroadcastList.getChildCount(); i < count; ++i) { mBroadcastList.getChildAt(i).setVisibility(GONE); } } static class BroadcastLayoutHolder { @BindView(R.id.image) public ImageView image; @BindView(R.id.text) public TextView textText; @BindView(R.id.time) public TimeTextView timeText; @BindView(R.id.time_action_space) public View timeActionSpace; @BindView(R.id.action) public TextView actionText; public long boundBroadcastId; public BroadcastLayoutHolder(View broadcastLayout) { ButterKnife.bind(this, broadcastLayout); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileBroadcastsLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,119
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import java.util.List; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.network.api.info.frodo.Broadcast; import me.zhanghai.android.douya.network.api.info.frodo.Diary; import me.zhanghai.android.douya.network.api.info.frodo.SimpleReview; import me.zhanghai.android.douya.network.api.info.frodo.SimpleUser; import me.zhanghai.android.douya.network.api.info.frodo.UserItems; import me.zhanghai.android.douya.ui.BarrierDataAdapter; import me.zhanghai.android.douya.util.ViewUtils; public class ProfileDataAdapter extends BarrierDataAdapter<ProfileDataAdapter.ViewHolder> { private enum Items { INTRODUCTION, BROADCASTS, FOLLOWSHIP, DIARIES, BOOKS, MOVIES, MUSIC, REVIEWS } private ProfileIntroductionLayout.Listener mListener; private Data mData; public ProfileDataAdapter(ProfileIntroductionLayout.Listener listener) { mListener = listener; } public void setData(Data data) { mData = data; notifyDataChanged(); } @Override public int getTotalItemCount() { return Items.values().length; } @Override protected boolean isItemLoaded(int position) { if (mData == null) { return false; } if (mData.user == null) { return false; } switch (Items.values()[position]) { case INTRODUCTION: // HACK: For better visual results, wait until broadcasts are loaded so that we have // sufficient height. // Fall through! //return true; case BROADCASTS: return mData.broadcastList != null; case FOLLOWSHIP: return mData.followingList != null; case DIARIES: return mData.diaryList != null; case BOOKS: return mData.userItemList != null; case MOVIES: return mData.userItemList != null; case MUSIC: return mData.userItemList != null; case REVIEWS: return mData.reviewList != null; default: throw new IllegalArgumentException(); } } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { int layoutRes; switch (Items.values()[viewType]) { case INTRODUCTION: layoutRes = R.layout.profile_introduction_item; break; case BROADCASTS: layoutRes = R.layout.profile_broadcasts_item; break; case FOLLOWSHIP: layoutRes = R.layout.profile_followship_item; break; case DIARIES: layoutRes = R.layout.profile_diaries_item; break; case BOOKS: layoutRes = R.layout.profile_books_item; break; case MOVIES: layoutRes = R.layout.profile_movies_item; break; case MUSIC: layoutRes = R.layout.profile_music_item; break; case REVIEWS: layoutRes = R.layout.profile_reviews_item; break; default: throw new IllegalArgumentException(); } View itemView; if (ViewUtils.isInLandscape(parent.getContext())) { itemView = ViewUtils.inflateWithTheme(layoutRes, parent, R.style.Theme_Douya); } else { itemView = ViewUtils.inflate(layoutRes, parent); } return new ViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { switch (Items.values()[position]) { case INTRODUCTION: { ProfileIntroductionLayout layout = ((ProfileIntroductionLayout) holder.getChild()); layout.bind(mData.user); layout.setListener(mListener); break; } case BROADCASTS: ((ProfileBroadcastsLayout) holder.getChild()).bind(mData.user, mData.broadcastList); break; case FOLLOWSHIP: ((ProfileFollowshipLayout) holder.getChild()).bind(mData.user, mData.followingList); break; case DIARIES: ((ProfileDiariesLayout) holder.getChild()).bind(mData.user, mData.diaryList); break; case BOOKS: ((ProfileBooksLayout) holder.getChild()).bind(mData.user, mData.userItemList); break; case MOVIES: ((ProfileMoviesLayout) holder.getChild()).bind(mData.user, mData.userItemList); break; case MUSIC: ((ProfileMusicLayout) holder.getChild()).bind(mData.user, mData.userItemList); break; case REVIEWS: ((ProfileReviewsLayout) holder.getChild()).bind(mData.user, mData.reviewList); break; default: throw new IllegalArgumentException(); } } public static class Data { public User user; public List<Broadcast> broadcastList; public List<SimpleUser> followingList; public List<Diary> diaryList; public List<UserItems> userItemList; public List<SimpleReview> reviewList; public Data(User user, List<Broadcast> broadcastList, List<SimpleUser> followingList, List<Diary> diaryList, List<UserItems> userItemList, List<SimpleReview> reviewList) { this.user = user; this.broadcastList = broadcastList; this.followingList = followingList; this.diaryList = diaryList; this.userItemList = userItemList; this.reviewList = reviewList; } } static class ViewHolder extends RecyclerView.ViewHolder { public ViewHolder(View itemView) { super(itemView); } public View getChild() { return ((ViewGroup) itemView).getChildAt(0); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileDataAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,252
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import androidx.core.view.ViewCompat; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.ui.FriendlyCardView; import me.zhanghai.android.douya.util.ViewUtils; public class ProfileIntroductionLayout extends FriendlyCardView { @BindView(R.id.title) TextView mTitleText; @BindView(R.id.content) TextView mContentText; private Listener mListener; public ProfileIntroductionLayout(Context context) { super(context); init(); } public ProfileIntroductionLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ProfileIntroductionLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { ViewUtils.inflateInto(R.layout.profile_introduction_layout, this); ButterKnife.bind(this); } public void setListener(Listener listener) { mListener = listener; } public void bind(String introduction) { introduction = introduction // \h requires Java 8. //.replaceFirst("^(\\h*\\n)*", "") //.replaceFirst("(\\n\\h*)*\\n?$", ""); .replaceFirst( "^([ \\t\\xA0\\u1680\\u180e\\u2000-\\u200a\\u202f\\u205f\\u3000]*\\n)*", "") .replaceFirst( "(\\n[ \\t\\xA0\\u1680\\u180e\\u2000-\\u200a\\u202f\\u205f\\u3000]*)*\\n?$", ""); if (!TextUtils.isEmpty(introduction)) { final String finalIntroduction = introduction; mTitleText.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { onCopyText(finalIntroduction); } }); Drawable selectableItemBackground = ViewUtils.getDrawableFromAttrRes( R.attr.selectableItemBackground, getContext()); // ?selectableItemBackground is a nine-patch drawable which reports its padding (of 0). boolean shouldSavePadding = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP; if (shouldSavePadding) { ViewUtils.setBackgroundPreservingPadding(mTitleText, selectableItemBackground); } else { ViewCompat.setBackground(mTitleText, selectableItemBackground); } mContentText.setText(introduction); } else { mTitleText.setOnClickListener(null); mTitleText.setClickable(false); ViewCompat.setBackground(mTitleText, null); mContentText.setText(R.string.profile_introduction_empty); } } public void bind(User user) { bind(user.introduction); } private void onCopyText(String text) { if (mListener != null) { mListener.onCopyText(text); } } public interface Listener { void onCopyText(String text); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileIntroductionLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
704
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.util.AttributeSet; import me.zhanghai.android.douya.link.UriHandler; import me.zhanghai.android.douya.network.api.info.frodo.CollectableItem; public class ProfileBooksLayout extends ProfileItemsLayout { public ProfileBooksLayout(Context context) { super(context); } public ProfileBooksLayout(Context context, AttributeSet attrs) { super(context, attrs); } public ProfileBooksLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected CollectableItem.Type getItemType() { return CollectableItem.Type.BOOK; } @Override protected void onViewPrimaryItems() { // FIXME UriHandler.open(String.format("path_to_url", getUserIdOrUid()), getContext()); } @Override protected void onViewSecondaryItems() { // FIXME UriHandler.open(String.format("path_to_url", getUserIdOrUid()), getContext()); } @Override protected void onViewTertiaryItems() { // FIXME UriHandler.open(String.format("path_to_url", getUserIdOrUid()), getContext()); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileBooksLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
268
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import me.zhanghai.android.douya.network.api.info.apiv2.SimpleUser; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.util.FragmentUtils; public class ProfileActivity extends AppCompatActivity { private static final String KEY_PREFIX = ProfileFragment.class.getName() + '.'; private static final String EXTRA_USER_ID_OR_UID = KEY_PREFIX + "user_id_or_uid"; private static final String EXTRA_SIMPLE_USER = KEY_PREFIX + "simple_user"; private static final String EXTRA_USER_INFO = KEY_PREFIX + "user_info"; private ProfileFragment mFragment; public static Intent makeIntent(String userIdOrUid, Context context) { return new Intent(context, ProfileActivity.class) .putExtra(EXTRA_USER_ID_OR_UID, userIdOrUid); } public static Intent makeIntent(SimpleUser simpleUser, Context context) { return new Intent(context, ProfileActivity.class) .putExtra(EXTRA_SIMPLE_USER, simpleUser); } public static Intent makeIntent( me.zhanghai.android.douya.network.api.info.frodo.SimpleUser simpleUser, Context context) { return makeIntent(SimpleUser.fromFrodo(simpleUser), context); } public static Intent makeIntent(User user, Context context) { return new Intent(context, ProfileActivity.class) .putExtra(EXTRA_USER_INFO, user); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); overridePendingTransition(0, 0); // Calls ensureSubDecor(). findViewById(android.R.id.content); if (savedInstanceState == null) { Intent intent = getIntent(); String userIdOrUid = intent.getStringExtra(EXTRA_USER_ID_OR_UID); SimpleUser simpleUser = intent.getParcelableExtra(EXTRA_SIMPLE_USER); User user = intent.getParcelableExtra(EXTRA_USER_INFO); mFragment = ProfileFragment.newInstance(userIdOrUid, simpleUser, user); FragmentUtils.add(mFragment, this, android.R.id.content); } else { mFragment = FragmentUtils.findById(this, android.R.id.content); } } @Override public void onBackPressed() { mFragment.onBackPressed(); } @Override public void finish() { super.finish(); overridePendingTransition(0, 0); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileActivity.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
543
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.util.AttributeSet; import me.zhanghai.android.douya.link.UriHandler; import me.zhanghai.android.douya.network.api.info.frodo.CollectableItem; public class ProfileMusicLayout extends ProfileItemsLayout { public ProfileMusicLayout(Context context) { super(context); } public ProfileMusicLayout(Context context, AttributeSet attrs) { super(context, attrs); } public ProfileMusicLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected CollectableItem.Type getItemType() { return CollectableItem.Type.MUSIC; } @Override protected void onViewPrimaryItems() { // FIXME UriHandler.open(String.format("path_to_url", getUserIdOrUid()), getContext()); } @Override protected void onViewSecondaryItems() { // FIXME UriHandler.open(String.format("path_to_url", getUserIdOrUid()), getContext()); } @Override protected void onViewTertiaryItems() { // FIXME UriHandler.open(String.format("path_to_url", getUserIdOrUid()), getContext()); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileMusicLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
268
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.util.AttributeSet; import me.zhanghai.android.douya.link.UriHandler; import me.zhanghai.android.douya.network.api.info.frodo.CollectableItem; public class ProfileMoviesLayout extends ProfileItemsLayout { public ProfileMoviesLayout(Context context) { super(context); } public ProfileMoviesLayout(Context context, AttributeSet attrs) { super(context, attrs); } public ProfileMoviesLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected CollectableItem.Type getItemType() { return CollectableItem.Type.MOVIE; } @Override protected void onViewPrimaryItems() { // FIXME UriHandler.open(String.format("path_to_url", getUserIdOrUid()), getContext()); } @Override protected void onViewSecondaryItems() { // FIXME UriHandler.open(String.format("path_to_url", getUserIdOrUid()), getContext()); } @Override protected void onViewTertiaryItems() { // FIXME UriHandler.open(String.format("path_to_url", getUserIdOrUid()), getContext()); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileMoviesLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
269
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.app.Activity; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import java.util.List; import butterknife.BindView; import butterknife.BindViews; import butterknife.ButterKnife; import me.zhanghai.android.customtabshelper.CustomTabsHelperFragment; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.followship.content.FollowUserManager; import me.zhanghai.android.douya.link.NotImplementedManager; import me.zhanghai.android.douya.network.api.ApiError; import me.zhanghai.android.douya.network.api.info.frodo.Broadcast; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.network.api.info.frodo.Diary; import me.zhanghai.android.douya.network.api.info.frodo.SimpleReview; import me.zhanghai.android.douya.network.api.info.frodo.SimpleUser; import me.zhanghai.android.douya.network.api.info.frodo.UserItems; import me.zhanghai.android.douya.profile.content.ProfileResource; import me.zhanghai.android.douya.profile.util.ProfileUtils; import me.zhanghai.android.douya.ui.ContentStateLayout; import me.zhanghai.android.douya.ui.CopyTextDialogFragment; import me.zhanghai.android.douya.ui.DoubleClickToolbar; import me.zhanghai.android.douya.ui.WebViewActivity; import me.zhanghai.android.douya.util.DoubanUtils; import me.zhanghai.android.douya.util.FragmentUtils; import me.zhanghai.android.douya.util.LogUtils; import me.zhanghai.android.douya.util.ShareUtils; import me.zhanghai.android.douya.util.ToastUtils; import me.zhanghai.android.douya.util.ViewUtils; public class ProfileFragment extends Fragment implements ProfileResource.Listener, ProfileHeaderLayout.Listener, ProfileIntroductionLayout.Listener, ConfirmUnfollowUserDialogFragment.Listener { private static final String KEY_PREFIX = ProfileFragment.class.getName() + '.'; private static final String EXTRA_USER_ID_OR_UID = KEY_PREFIX + "user_id_or_uid"; private static final String EXTRA_SIMPLE_USER = KEY_PREFIX + "simple_user"; private static final String EXTRA_USER = KEY_PREFIX + "user"; @BindView(R.id.scroll) ProfileLayout mScrollLayout; @BindView(R.id.header) ProfileHeaderLayout mHeaderLayout; @BindView(R.id.dismiss) View mDismissView; @BindView(R.id.toolbar) DoubleClickToolbar mToolbar; @BindViews({ R.id.profile_header_animate_changes_layout_1, R.id.profile_header_animate_changes_layout_2 }) ViewGroup[] mAnimateChangesLayouts; @BindView(R.id.contentState) ContentStateLayout mContentStateLayout; @BindView(R.id.content) RecyclerView mContentList; private String mUserIdOrUid; private me.zhanghai.android.douya.network.api.info.apiv2.SimpleUser mSimpleUser; private User mUser; private ProfileResource mResource; private ProfileAdapter mAdapter; public static ProfileFragment newInstance( String userIdOrUid, me.zhanghai.android.douya.network.api.info.apiv2.SimpleUser simpleUser, User user) { //noinspection deprecation ProfileFragment fragment = new ProfileFragment(); FragmentUtils.getArgumentsBuilder(fragment) .putString(EXTRA_USER_ID_OR_UID, userIdOrUid) .putParcelable(EXTRA_SIMPLE_USER, simpleUser) .putParcelable(EXTRA_USER, user); return fragment; } /** * @deprecated Use {@link #newInstance(String, me.zhanghai.android.douya.network.api.info.apiv2.SimpleUser, User)} instead. */ public ProfileFragment() {} @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle arguments = getArguments(); mUserIdOrUid = arguments.getString(EXTRA_USER_ID_OR_UID); mSimpleUser = arguments.getParcelable(EXTRA_SIMPLE_USER); mUser = arguments.getParcelable(EXTRA_USER); setHasOptionsMenu(true); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { int layoutRes = ProfileUtils.shouldUseWideLayout(inflater.getContext()) ? R.layout.profile_fragment_wide : R.layout.profile_fragment; return inflater.inflate(layoutRes, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); CustomTabsHelperFragment.attachTo(this); mResource = ProfileResource.attachTo(mUserIdOrUid, mSimpleUser, mUser, this); mScrollLayout.setListener(new ProfileLayout.Listener() { @Override public void onEnterAnimationEnd() {} @Override public void onExitAnimationEnd() { getActivity().finish(); } }); if (savedInstanceState == null) { mScrollLayout.enter(); } mDismissView.setOnClickListener(view -> exit()); AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.setSupportActionBar(mToolbar); activity.getSupportActionBar().setTitle(null); if (mResource.hasUser()) { mHeaderLayout.bindUser(mResource.getUser()); } else if (mResource.hasSimpleUser()) { mHeaderLayout.bindSimpleUser(mResource.getSimpleUser()); } mHeaderLayout.setListener(this); mToolbar.setOnDoubleClickListener(view -> { if (!mScrollLayout.isHeaderCollapsed()) { return false; } mScrollLayout.animateHeaderViewScroll(false); return true; }); if (ViewUtils.hasSw600Dp(activity)) { mContentList.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); } else { mContentList.setLayoutManager(new LinearLayoutManager(activity)); } mAdapter = new ProfileAdapter(this); mContentList.setAdapter(mAdapter); mContentStateLayout.setLoading(); if (mResource.isAnyLoaded()) { mResource.notifyChangedIfLoaded(); } } @Override public void onDestroy() { super.onDestroy(); mResource.detach(); } public void onBackPressed() { exit(); } private void exit() { mScrollLayout.exit(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.profile, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); updateOptionsMenu(); } private void updateOptionsMenu() { // TODO: Block or unblock. } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_send_doumail: sendDoumail(); return true; case R.id.action_blacklist: // TODO NotImplementedManager.showNotYetImplementedToast(getActivity()); return true; case R.id.action_report_abuse: // TODO NotImplementedManager.showNotYetImplementedToast(getActivity()); return true; case R.id.action_share: share(); return true; case R.id.action_view_on_web: viewOnWeb(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onLoadError(int requestCode, ApiError error) { LogUtils.e(error.toString()); if (mAdapter.getItemCount() > 0) { mAdapter.setError(); } else { mContentStateLayout.setError(); } Activity activity = getActivity(); ToastUtils.show(ApiError.getErrorString(error, activity), activity); } @Override public void onUserChanged(int requestCode, User newUser) { // WORKAROUND: Fix for LayoutTransition visual glitch when view is scrolling. if (!mScrollLayout.isHeaderOpen()) { for (ViewGroup animateChangesLayout : mAnimateChangesLayouts) { animateChangesLayout.setLayoutTransition(null); } } mHeaderLayout.bindUser(newUser); updateOptionsMenu(); } @Override public void onUserWriteStarted(int requestCode) { mHeaderLayout.bindUser(mResource.getUser()); } @Override public void onUserWriteFinished(int requestCode) { mHeaderLayout.bindUser(mResource.getUser()); } @Override public void onChanged(int requestCode, User newUser, List<Broadcast> newBroadcastList, List<SimpleUser> newFollowingList, List<Diary> newDiaryList, List<UserItems> newUserItemList, List<SimpleReview> newReviewList) { mAdapter.setData(new ProfileDataAdapter.Data(newUser, newBroadcastList, newFollowingList, newDiaryList, newUserItemList, newReviewList)); if (mAdapter.getItemCount() > 0) { mContentStateLayout.setLoaded(true); } updateOptionsMenu(); } private void sendDoumail() { String userIdOrUid = mResource.getUserIdOrUid(); NotImplementedManager.sendDoumail(userIdOrUid, getActivity()); } private void share() { ShareUtils.shareText(makeUrl(), getActivity()); } private void viewOnWeb() { startActivity(WebViewActivity.makeIntent(makeUrl(), true, getActivity())); } private String makeUrl() { if (mResource.hasSimpleUser()) { return mResource.getSimpleUser().getUrl(); } else { return DoubanUtils.makeUserUrl(mResource.getUserIdOrUid()); } } @Override public void onEditProfile(User user) { NotImplementedManager.editProfile(getActivity()); } @Override public void onFollowUser(User user, boolean follow) { if (follow) { FollowUserManager.getInstance().write(user, true, getActivity()); } else { ConfirmUnfollowUserDialogFragment.show(this); } } @Override public void onUnfollowUser() { FollowUserManager.getInstance().write(mResource.getUser(), false, getActivity()); } @Override public void onCopyText(String text) { CopyTextDialogFragment.show(text, this); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileFragment.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
2,251
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import androidx.recyclerview.widget.RecyclerView; import me.zhanghai.android.douya.ui.BarrierAdapter; public class ProfileAdapter extends BarrierAdapter { private ProfileDataAdapter mDataAdapter; public ProfileAdapter(ProfileIntroductionLayout.Listener listener) { super(new ProfileDataAdapter(listener)); RecyclerView.Adapter<?>[] adapters = getAdapters(); mDataAdapter = (ProfileDataAdapter) adapters[0]; } public void setData(ProfileDataAdapter.Data data) { mDataAdapter.setData(data); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
117
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.network.api.info.frodo.CollectableItem; import me.zhanghai.android.douya.network.api.info.frodo.ItemCollectionState; import me.zhanghai.android.douya.network.api.info.frodo.UserItems; import me.zhanghai.android.douya.ui.FriendlyCardView; import me.zhanghai.android.douya.util.ViewUtils; public abstract class ProfileItemsLayout extends FriendlyCardView { @BindView(R.id.title) TextView mTitleText; @BindView(R.id.item_list) RecyclerView mItemList; @BindView(R.id.empty) TextView mEmptyView; @BindView(R.id.view_more) TextView mViewMoreText; @BindView(R.id.secondary) TextView mSecondaryText; @BindView(R.id.tertiary) TextView mTertiaryText; private String mUserIdOrUid; private ProfileItemAdapter mItemAdapter; public ProfileItemsLayout(Context context) { super(context); init(); } public ProfileItemsLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ProfileItemsLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { ViewUtils.inflateInto(R.layout.profile_items_layout, this); ButterKnife.bind(this); mItemList.setHasFixedSize(true); mItemList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false)); mItemAdapter = new ProfileItemAdapter(); mItemList.setAdapter(mItemAdapter); } protected void bind(UserItems primaryItems, UserItems secondaryItems, UserItems tertiaryItems) { final Context context = getContext(); ItemCollectionState state = primaryItems.getState(); CollectableItem.Type type = primaryItems.getType(); String stateString = state.getString(type, context); mTitleText.setText(stateString); OnClickListener viewMoreListener = new OnClickListener() { @Override public void onClick(View view) { onViewPrimaryItems(); } }; mTitleText.setOnClickListener(viewMoreListener); mViewMoreText.setOnClickListener(viewMoreListener); mItemAdapter.replace(primaryItems.items); ViewUtils.setVisibleOrGone(mItemList, !primaryItems.items.isEmpty()); mEmptyView.setText(context.getString(R.string.profile_items_empty_format, stateString, type.getName(context))); ViewUtils.setVisibleOrGone(mEmptyView, primaryItems.items.isEmpty()); if (primaryItems.total > primaryItems.items.size()) { mViewMoreText.setText(context.getString(R.string.view_more_with_count_format, primaryItems.total)); } else { mViewMoreText.setVisibility(GONE); } if (secondaryItems != null && secondaryItems.total > 0) { mSecondaryText.setText(context.getString(R.string.profile_items_non_primary_format, secondaryItems.getState().getString(secondaryItems.getType(), context), secondaryItems.total)); mSecondaryText.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { onViewSecondaryItems(); } }); } else { mSecondaryText.setVisibility(GONE); } if (tertiaryItems != null && tertiaryItems.total > 0) { mTertiaryText.setText(context.getString(R.string.profile_items_non_primary_format, tertiaryItems.getState().getString(tertiaryItems.getType(), context), tertiaryItems.total)); mTertiaryText.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { onViewTertiaryItems(); } }); } else { mTertiaryText.setVisibility(GONE); } } public void bind(User user, List<UserItems> userItemList) { mUserIdOrUid = user.getIdOrUid(); UserItems primaryItems = null; UserItems secondaryItems = null; UserItems tertiaryItems = null; CollectableItem.Type type = getItemType(); for (UserItems userItems : userItemList) { if (userItems.getType() == type) { switch (userItems.getState()) { case TODO: tertiaryItems = userItems; break; case DOING: secondaryItems = userItems; break; case DONE: primaryItems = userItems; break; } } } if (primaryItems == null) { // HACK: Frodo API omits the done item if empty, but we need it. primaryItems = new UserItems(); //noinspection deprecation primaryItems.type = type.getApiString(); //noinspection deprecation primaryItems.state = ItemCollectionState.DONE.getApiString(); } bind(primaryItems, secondaryItems, tertiaryItems); } protected String getUserIdOrUid() { return mUserIdOrUid; } protected abstract CollectableItem.Type getItemType(); protected abstract void onViewPrimaryItems(); protected abstract void onViewSecondaryItems(); protected abstract void onViewTertiaryItems(); } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileItemsLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,128
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.util.AttributeSet; import android.view.View; import butterknife.BindDimen; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.profile.util.ProfileUtils; import me.zhanghai.android.douya.ui.FlexibleSpaceContentLayout; public class ProfileContentLayout extends FlexibleSpaceContentLayout { @BindDimen(R.dimen.screen_edge_horizontal_margin) int mScreenEdgeHorizontalMargin; @BindDimen(R.dimen.single_line_list_item_height) int mSingleLineListItemHeight; @BindDimen(R.dimen.card_vertical_margin) int mCardVerticalMargin; @BindDimen(R.dimen.card_shadow_vertical_margin) int mCardShadowVerticalMargin; @BindDimen(R.dimen.horizontal_divider_height) int mHorizontalDividerHeight; private boolean mUseWideLayout; public ProfileContentLayout(Context context) { super(context); init(); } public ProfileContentLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ProfileContentLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public ProfileContentLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { ButterKnife.bind(this); mUseWideLayout = ProfileUtils.shouldUseWideLayout(getContext()); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mUseWideLayout) { int width = MeasureSpec.getSize(widthMeasureSpec); int paddingLeft = ProfileUtils.getAppBarWidth(width, getContext()) - mScreenEdgeHorizontalMargin; setPadding(paddingLeft, getPaddingTop(), getPaddingRight(), getPaddingBottom()); int height = MeasureSpec.getSize(heightMeasureSpec); View contentView = getContentView(); int contentPaddingTop = height * 2 / 5 - mSingleLineListItemHeight - (mCardVerticalMargin - mCardShadowVerticalMargin) - mHorizontalDividerHeight; contentView.setPadding(contentView.getPaddingLeft(), contentPaddingTop, contentView.getPaddingRight(), contentView.getPaddingBottom()); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileContentLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
513
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.followship.ui.FollowerListActivity; import me.zhanghai.android.douya.followship.ui.FollowingListActivity; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.network.api.info.frodo.SimpleUser; import me.zhanghai.android.douya.ui.FriendlyCardView; import me.zhanghai.android.douya.util.ImageUtils; import me.zhanghai.android.douya.util.ViewUtils; public class ProfileFollowshipLayout extends FriendlyCardView { private static final int USER_COUNT_MAX = 5; @BindView(R.id.title) TextView mTitleText; @BindView(R.id.following_list) LinearLayout mFollowingList; @BindView(R.id.empty) View mEmptyView; @BindView(R.id.view_more) TextView mViewMoreText; @BindView(R.id.follower) TextView mFollwerText; public ProfileFollowshipLayout(Context context) { super(context); init(); } public ProfileFollowshipLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ProfileFollowshipLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { ViewUtils.inflateInto(R.layout.profile_followship_layout, this); ButterKnife.bind(this); } public void bind(final User userInfo, List<SimpleUser> followingList) { final Context context = getContext(); OnClickListener viewFollowingListListener = new OnClickListener() { @Override public void onClick(View view) { context.startActivity(FollowingListActivity.makeIntent(userInfo.getIdOrUid(), context)); } }; mTitleText.setOnClickListener(viewFollowingListListener); mViewMoreText.setOnClickListener(viewFollowingListListener); int i = 0; for (final SimpleUser user : followingList) { if (i >= USER_COUNT_MAX) { break; } if (i >= mFollowingList.getChildCount()) { ViewUtils.inflateInto(R.layout.profile_user_item, mFollowingList); } View userLayout = mFollowingList.getChildAt(i); UserLayoutHolder holder = (UserLayoutHolder) userLayout.getTag(); if (holder == null) { holder = new UserLayoutHolder(userLayout); userLayout.setTag(holder); } ImageUtils.loadAvatar(holder.avatarImage, user.avatar); holder.nameText.setText(user.name); userLayout.setOnClickListener(view -> context.startActivity(ProfileActivity.makeIntent( user, context))); ++i; } ViewUtils.setVisibleOrGone(mFollowingList, i != 0); ViewUtils.setVisibleOrGone(mEmptyView, i == 0); if (userInfo.followingCount > i) { mViewMoreText.setText(context.getString(R.string.view_more_with_count_format, userInfo.followingCount)); } else { mViewMoreText.setVisibility(GONE); } for (int count = mFollowingList.getChildCount(); i < count; ++i) { ViewUtils.setVisibleOrGone(mFollowingList.getChildAt(i), false); } if (userInfo.followerCount > 0) { mFollwerText.setText(context.getString(R.string.profile_follower_count_format, userInfo.followerCount)); mFollwerText.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { context.startActivity(FollowerListActivity.makeIntent(userInfo.getIdOrUid(), context)); } }); } else { mFollwerText.setVisibility(GONE); } } static class UserLayoutHolder { @BindView(R.id.avatar) public ImageView avatarImage; @BindView(R.id.name) public TextView nameText; public UserLayoutHolder(View broadcastLayout) { ButterKnife.bind(this, broadcastLayout); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileFollowshipLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
895
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.Outline; import android.os.Build; import androidx.core.widget.TextViewCompat; import androidx.appcompat.widget.Toolbar; import android.util.AttributeSet; import android.view.View; import android.view.ViewOutlineProvider; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import butterknife.BindColor; import butterknife.BindDimen; import butterknife.BindView; import butterknife.ButterKnife; import de.hdodenhof.circleimageview.CircleImageView; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.followship.content.FollowUserManager; import me.zhanghai.android.douya.gallery.ui.GalleryActivity; import me.zhanghai.android.douya.network.api.info.apiv2.SimpleUser; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.profile.util.ProfileUtils; import me.zhanghai.android.douya.ui.FlexibleSpaceHeaderView; import me.zhanghai.android.douya.ui.JoinTimeLocationAutoGoneTextView; import me.zhanghai.android.douya.ui.WhiteIndeterminateProgressIconDrawable; import me.zhanghai.android.douya.util.AppUtils; import me.zhanghai.android.douya.util.ImageUtils; import me.zhanghai.android.douya.util.MathUtils; import me.zhanghai.android.douya.util.StatusBarColorUtils; import me.zhanghai.android.douya.util.ViewUtils; /** * Set the initial layout_height to match_parent or wrap_content instead a specific value so that * the view measures itself correctly for the first time. */ public class ProfileHeaderLayout extends FrameLayout implements FlexibleSpaceHeaderView { @BindColor(R.color.system_window_scrim) int mStatusBarColorScrim; private int mStatusBarColorFullscreen; @BindDimen(R.dimen.profile_large_avatar_size) int mLargeAvatarSize; @BindDimen(R.dimen.profile_small_avatar_size) int mSmallAvatarSize; @BindDimen(R.dimen.screen_edge_horizontal_margin) int mScreenEdgeHorizontalMargin; @BindDimen(R.dimen.toolbar_height) int mToolbarHeight; @BindView(R.id.dismiss) View mDismissView; @BindView(R.id.appBar) LinearLayout mAppBarLayout; @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.toolbar_username) TextView mToolbarUsernameText; @BindView(R.id.username) TextView mUsernameText; @BindView(R.id.signature) TextView mSignatureText; @BindView(R.id.join_time_location) JoinTimeLocationAutoGoneTextView mJoinTimeLocationText; @BindView(R.id.follow) Button mFollowButton; @BindView(R.id.avatar_container) FrameLayout mAvatarContainerLayout; @BindView(R.id.avatar) CircleImageView mAvatarImage; private boolean mUseWideLayout; private int mInsetTop; private int mMaxHeight; private int mScroll; private Listener mListener; public ProfileHeaderLayout(Context context) { super(context); init(); } public ProfileHeaderLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ProfileHeaderLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public ProfileHeaderLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void init() { // HACK: We need to delegate the outline so that elevation can work. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setOutlineProvider(new ViewOutlineProvider() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void getOutline(View view, Outline outline) { // We cannot use mAppBarLayout.getOutlineProvider.getOutline() because the // bounds of it is not kept in sync when this method is called. // HACK: Workaround the fact that we must provided an outline before we are // measured. int height = getHeight(); int top = height > 0 ? height - computeVisibleAppBarHeight() : 0; outline.setRect(0, top, getWidth(), height); } }); } } @Override protected void onFinishInflate() { super.onFinishInflate(); ButterKnife.bind(this); Context context = getContext(); mStatusBarColorFullscreen = ViewUtils.getColorFromAttrRes(R.attr.colorPrimaryDark, 0, context); mUseWideLayout = ProfileUtils.shouldUseWideLayout(context); StatusBarColorUtils.set(mStatusBarColorScrim, (Activity) context); } public void setListener(Listener listener) { mListener = listener; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxHeight, MeasureSpec.EXACTLY); } int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); int dismissViewHeight = height - computeVisibleAppBarHeight(); mDismissView.getLayoutParams().height = dismissViewHeight; MarginLayoutParams appBarLayoutLayoutParams = (MarginLayoutParams) mAppBarLayout.getLayoutParams(); appBarLayoutLayoutParams.topMargin = dismissViewHeight; // So that the layout remains stable. appBarLayoutLayoutParams.height = getAppBarMaxHeight(); int appBarWidth = ProfileUtils.getAppBarWidth(width, getContext()); if (mUseWideLayout) { mAppBarLayout.setPadding(mAppBarLayout.getPaddingLeft(), mAppBarLayout.getPaddingTop(), width - appBarWidth, mAppBarLayout.getPaddingBottom()); } int largeAvatarSizeHalf = mLargeAvatarSize / 2; int avatarMarginTop = dismissViewHeight - mInsetTop - largeAvatarSizeHalf; int smallAvatarMarginTop = (mToolbarHeight - mSmallAvatarSize) / 2; float avatarHorizontalFraction = avatarMarginTop < smallAvatarMarginTop ? MathUtils.unlerp(smallAvatarMarginTop, -largeAvatarSizeHalf, avatarMarginTop) : 0; avatarMarginTop = Math.max(smallAvatarMarginTop, avatarMarginTop) + mInsetTop; int avatarMarginLeft = MathUtils.lerpInt(appBarWidth / 2 - largeAvatarSizeHalf, mScreenEdgeHorizontalMargin, avatarHorizontalFraction); MarginLayoutParams avatarContainerLayoutParams = (MarginLayoutParams) mAvatarContainerLayout.getLayoutParams(); avatarContainerLayoutParams.leftMargin = avatarMarginLeft; avatarContainerLayoutParams.topMargin = avatarMarginTop; float avatarScale = MathUtils.lerp(1, (float) mSmallAvatarSize / mLargeAvatarSize, avatarHorizontalFraction); mAvatarContainerLayout.setPivotX(0); mAvatarContainerLayout.setPivotY(0); mAvatarContainerLayout.setScaleX(avatarScale); mAvatarContainerLayout.setScaleY(avatarScale); for (int i = 0, count = mAppBarLayout.getChildCount(); i < count; ++i) { View child = mAppBarLayout.getChildAt(i); if (child != mToolbar) { child.setAlpha(Math.max(0, 1 - getFraction() * 2)); } } mToolbarUsernameText.setAlpha(Math.max(0, getFraction() * 2 - 1)); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public void setInsetTop(int insetTop) { if (mInsetTop == insetTop) { return; } mInsetTop = insetTop; requestLayout(); } private int getAppBarMinHeight() { if (mUseWideLayout) { return getAppBarMaxHeight(); } else { // So that we don't need to wait until measure. return mToolbar.getLayoutParams().height; } } private int getAppBarMaxHeight() { return mUseWideLayout ? mMaxHeight * 3 / 5 : mMaxHeight / 2; } private int computeVisibleAppBarHeight() { return MathUtils.lerpInt(getAppBarMaxHeight(), getAppBarMinHeight(), getFraction()); } private float getFraction() { int scrollExtent = getScrollExtent(); return scrollExtent > 0 ? (float) mScroll / scrollExtent : 0; } @Override public int getScroll() { return mScroll; } @Override public int getScrollExtent() { return mMaxHeight - getMinHeight(); } @Override public void scrollTo(int scroll) { int scrollExtent = getScrollExtent(); scroll = MathUtils.constrain(scroll, 0, scrollExtent); if (mScroll == scroll) { return; } ViewUtils.setHeight(this, mMaxHeight - scroll); int oldScroll = mScroll; mScroll = scroll; if (oldScroll < scrollExtent && mScroll == scrollExtent) { StatusBarColorUtils.animateTo(mStatusBarColorFullscreen, AppUtils.getActivityFromContext(getContext())); } else if (oldScroll == scrollExtent && mScroll < oldScroll) { StatusBarColorUtils.animateTo(mStatusBarColorScrim, AppUtils.getActivityFromContext(getContext())); } } private int getMinHeight() { if (mUseWideLayout) { return mMaxHeight; } else { // So that we don't need to wait until measure. return mToolbar.getLayoutParams().height + mInsetTop; } } // Should be called by ProfileLayout.onMeasure() before its super call. public void setMaxHeight(int maxHeight) { if (mMaxHeight == maxHeight) { return; } mMaxHeight = maxHeight; ViewUtils.setHeight(mAppBarLayout, mMaxHeight); } public void bindSimpleUser(SimpleUser simpleUser) { final String largeAvatar = simpleUser.getLargeAvatarOrAvatar(); ImageUtils.loadProfileAvatarAndFadeIn(mAvatarImage, largeAvatar); final Context context = getContext(); mAvatarImage.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { context.startActivity(GalleryActivity.makeIntent(largeAvatar, context)); } }); mToolbarUsernameText.setText(simpleUser.name); mUsernameText.setText(simpleUser.name); mSignatureText.setText(null); mJoinTimeLocationText.setText(null); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(mFollowButton, 0, 0, 0, 0); mFollowButton.setVisibility(GONE); } public void bindUser(final User user) { final Context context = getContext(); if (!ViewUtils.isVisible(mAvatarImage)) { // HACK: Don't load avatar again if already loaded by bindSimpleUser(). final String largeAvatar = user.getLargeAvatarOrAvatar(); ImageUtils.loadProfileAvatarAndFadeIn(mAvatarImage, largeAvatar); mAvatarImage.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { context.startActivity(GalleryActivity.makeIntent(largeAvatar, context)); } }); } mToolbarUsernameText.setText(user.name); mUsernameText.setText(user.name); mSignatureText.setText(user.signature); mJoinTimeLocationText.setJoinTimeAndLocation(user.createTime, user.locationName); if (user.isOneself()) { TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(mFollowButton, R.drawable.edit_icon_white_24dp, 0, 0, 0); mFollowButton.setText(R.string.profile_edit); mFollowButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (mListener != null) { mListener.onEditProfile(user); } } }); } else { FollowUserManager followUserManager = FollowUserManager.getInstance(); String userIdOrUid = user.getIdOrUid(); if (followUserManager.isWriting(userIdOrUid)) { TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(mFollowButton, new WhiteIndeterminateProgressIconDrawable(context), null, null, null); mFollowButton.setText(followUserManager.isWritingFollow(userIdOrUid) ? R.string.user_following : R.string.user_unfollowing); } else { int followDrawableId; int followStringId; if (user.isFollowed) { if (user.isFollower) { followDrawableId = R.drawable.mutual_icon_white_24dp; followStringId = R.string.profile_following_mutual; } else { followDrawableId = R.drawable.ok_icon_white_24dp; followStringId = R.string.profile_following; } } else { followDrawableId = R.drawable.add_icon_white_24dp; followStringId = R.string.profile_follow; } TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(mFollowButton, followDrawableId, 0, 0, 0); mFollowButton.setText(followStringId); } mFollowButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (mListener != null) { mListener.onFollowUser(user, !user.isFollowed); } } }); } mFollowButton.setVisibility(VISIBLE); } public interface Listener { void onEditProfile(User user); void onFollowUser(User user, boolean follow); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileHeaderLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
2,948
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.content.Intent; import androidx.core.view.ViewCompat; import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Space; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.item.ui.ItemActivities; import me.zhanghai.android.douya.link.UriHandler; import me.zhanghai.android.douya.network.api.info.frodo.CollectableItem; import me.zhanghai.android.douya.ui.RatioFrameLayout; import me.zhanghai.android.douya.ui.SimpleAdapter; import me.zhanghai.android.douya.util.DrawableUtils; import me.zhanghai.android.douya.util.ImageUtils; import me.zhanghai.android.douya.util.RecyclerViewUtils; import me.zhanghai.android.douya.util.ViewUtils; public class ProfileItemAdapter extends SimpleAdapter<CollectableItem, ProfileItemAdapter.ViewHolder> { public ProfileItemAdapter() { setHasStableIds(true); } @Override public long getItemId(int position) { return getItem(position).id; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewHolder holder = new ViewHolder(ViewUtils.inflate(R.layout.profile_item_item, parent)); ViewCompat.setBackground(holder.scrimView, DrawableUtils.makeScrimDrawable()); return holder; } @Override public void onBindViewHolder(final ViewHolder holder, int position) { final CollectableItem item = getItem(position); float ratio = 1; switch (item.getType()) { case BOOK: case EVENT: case MOVIE: case TV: ratio = 2f / 3f; break; } holder.itemLayout.setRatio(ratio); final Context context = RecyclerViewUtils.getContext(holder); holder.itemLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // TODO Intent intent = ItemActivities.makeIntent(item, context); if (intent != null) { context.startActivity(intent); } else { UriHandler.open(item.url, context); } } }); ImageUtils.loadImage(holder.coverImage, item.cover.getLargeUrl()); holder.titleText.setText(item.title); // FIXME: This won't work properly if items are changed. ViewUtils.setVisibleOrGone(holder.dividerSpace, position != getItemCount() - 1); } static class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.item) public RatioFrameLayout itemLayout; @BindView(R.id.cover) public ImageView coverImage; @BindView(R.id.scrim) public View scrimView; @BindView(R.id.title) public TextView titleText; @BindView(R.id.divider) public Space dividerSpace; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileItemAdapter.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
652
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.os.Build; import androidx.interpolator.view.animation.FastOutLinearInInterpolator; import androidx.interpolator.view.animation.LinearOutSlowInInterpolator; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ViewGroup; import android.view.WindowInsets; import butterknife.BindColor; import butterknife.BindInt; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.profile.util.ProfileUtils; import me.zhanghai.android.douya.ui.FlexibleSpaceLayout; import me.zhanghai.android.douya.ui.IntProperty; import me.zhanghai.android.douya.util.AppUtils; import me.zhanghai.android.douya.util.ColorUtils; import me.zhanghai.android.douya.util.StatusBarColorUtils; import me.zhanghai.android.douya.util.ViewUtils; public class ProfileLayout extends FlexibleSpaceLayout { @BindInt(android.R.integer.config_shortAnimTime) int mShortAnimationTime; @BindColor(R.color.system_window_scrim) int mStatusBarColor; @BindColor(R.color.dark_70_percent) int mBackgroundColor; private ViewGroup mOffsetContainer; private ProfileHeaderLayout mProfileHeaderLayout; private boolean mUseWideLayout; private boolean mExiting; private ColorDrawable mWindowBackground; private Listener mListener; public ProfileLayout(Context context) { super(context); init(); } public ProfileLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ProfileLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public ProfileLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { ButterKnife.bind(this); Context context = getContext(); mUseWideLayout = ProfileUtils.shouldUseWideLayout(context); ViewUtils.setLayoutFullscreen(this); mWindowBackground = new ColorDrawable(mBackgroundColor); AppUtils.getActivityFromContext(context).getWindow() .setBackgroundDrawable(mWindowBackground); } @Override protected void onFinishInflate() { super.onFinishInflate(); // HACK: Coupled with specific XML hierarchy. mOffsetContainer = (ViewGroup) getChildAt(0); mProfileHeaderLayout = (ProfileHeaderLayout) mOffsetContainer.getChildAt(0); } @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) @Override public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { setPadding(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(), 0); mProfileHeaderLayout.setInsetTop(insets.getSystemWindowInsetTop()); return insets.consumeSystemWindowInsets(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = MeasureSpec.getSize(heightMeasureSpec); int headerMaxHeight = mUseWideLayout ? height : height * 2 / 3; mProfileHeaderLayout.setMaxHeight(headerMaxHeight); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public int getOffset() { // View.offsetTopAndBottom causes transient invalid layout position when animating in. return (int) mOffsetContainer.getTranslationY(); } public void offsetTo(int offset) { if (offset < 0) { offset = 0; } if (getOffset() == offset) { return; } mOffsetContainer.setTranslationY(offset); updateStatusBarAndWindowBackground(offset); } public void offsetBy(int delta) { offsetTo(getOffset() + delta); } private void updateStatusBarAndWindowBackground(int offset) { float fraction = Math.max(0, 1 - (float) offset / getHeight()); int alpha = (int) (fraction * 0xFF); int statusBarColor = ColorUtils.blendAlphaComponent(mStatusBarColor, alpha); StatusBarColorUtils.set(statusBarColor, AppUtils.getActivityFromContext(getContext())); mWindowBackground.setAlpha(alpha); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (mExiting) { return false; } return super.onInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { if (mExiting) { return false; } return super.onTouchEvent(event); } @Override public boolean onGenericMotionEvent(MotionEvent event) { if (mExiting) { return false; } return super.onGenericMotionEvent(event); } @Override protected void onDrag(MotionEvent event, float delta) { if (delta > 0) { int oldScroll = getScroll(); scrollBy((int) -delta); delta += getScroll() - oldScroll; offsetBy((int) delta); } else { int oldOffset = getOffset(); offsetBy((int) delta); delta -= getOffset() - oldOffset; int oldScroll = getScroll(); scrollBy((int) -delta); delta += getScroll() - oldScroll; if (delta < 0) { pullEdgeEffectBottom(event, delta); } } } @Override protected void onDragEnd(boolean cancelled) { if (getOffset() > 0) { exit(); } else { super.onDragEnd(cancelled); } } @Override protected boolean shouldDrawEdgeEffectBottom() { return !mUseWideLayout; } public Listener getListener() { return mListener; } public void setListener(Listener listener) { mListener = listener; } public void enter() { ViewUtils.postOnPreDraw(this, new Runnable() { @Override public void run() { animateEnter(); } }); } private void animateEnter() { ObjectAnimator animator = ObjectAnimator.ofInt(this, OFFSET, getHeight(), 0); animator.setDuration(mShortAnimationTime); animator.setInterpolator(new LinearOutSlowInInterpolator()); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (mListener != null) { mListener.onEnterAnimationEnd(); } } }); animator.start(); } public void exit() { if (mExiting) { return; } mExiting = true; abortScrollerAnimation(); recycleVelocityTrackerIfHas(); animateExit(); } private void animateExit() { int offset = getOffset(); int height = getHeight(); if (offset >= height) { mListener.onExitAnimationEnd(); return; } ObjectAnimator animator = ObjectAnimator.ofInt(this, OFFSET, offset, height); animator.setDuration(mShortAnimationTime); animator.setInterpolator(new FastOutLinearInInterpolator()); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (mListener != null) { mListener.onExitAnimationEnd(); } } }); animator.start(); } public static final IntProperty<ProfileLayout> OFFSET = new IntProperty<ProfileLayout>("offset") { @Override public Integer get(ProfileLayout object) { return object.getOffset(); } @Override public void setValue(ProfileLayout object, int value) { object.offsetTo(value); } }; public interface Listener { void onEnterAnimationEnd(); void onExitAnimationEnd(); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
1,681
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.util; import android.content.Context; import android.content.res.Resources; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.util.CardUtils; import me.zhanghai.android.douya.util.ViewUtils; public class ProfileUtils { private ProfileUtils() {} public static boolean shouldUseWideLayout(Context context) { return ViewUtils.hasSw600Dp(context) ? ViewUtils.isInLandscape(context) : !CardUtils.isFullWidth(context); } public static int getAppBarWidth(int width, Context context) { if (shouldUseWideLayout(context)) { if (CardUtils.getColumnCount(context) == 2) { return width * 2 / 5; } else { Resources resources = context.getResources(); int cardListHorizontalPadding = resources .getDimensionPixelOffset(R.dimen.card_list_horizontal_padding); int cardHorizontalMargin = resources.getDimensionPixelOffset(R.dimen.card_horizontal_margin); int cardShadowHorizontalMargin = resources.getDimensionPixelOffset(R.dimen.card_shadow_horizontal_margin); return (width - 2 * cardListHorizontalPadding) / 3 + cardListHorizontalPadding + cardHorizontalMargin - cardShadowHorizontalMargin; } } else { return width; } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/util/ProfileUtils.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
293
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.ui; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import me.zhanghai.android.douya.R; import me.zhanghai.android.douya.link.UriHandler; import me.zhanghai.android.douya.network.api.info.apiv2.User; import me.zhanghai.android.douya.network.api.info.frodo.Diary; import me.zhanghai.android.douya.ui.FriendlyCardView; import me.zhanghai.android.douya.util.ImageUtils; import me.zhanghai.android.douya.util.StringUtils; import me.zhanghai.android.douya.util.ViewUtils; public class ProfileDiariesLayout extends FriendlyCardView { private static final int DIARY_COUNT_MAX = 3; @BindView(R.id.title) TextView mTitleText; @BindView(R.id.diary_list) LinearLayout mDiaryList; @BindView(R.id.empty) View mEmptyView; @BindView(R.id.view_more) TextView mViewMoreText; public ProfileDiariesLayout(Context context) { super(context); init(); } public ProfileDiariesLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ProfileDiariesLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { ViewUtils.inflateInto(R.layout.profile_diaries_layout, this); ButterKnife.bind(this); } public void bind(final User user, List<Diary> diaryList) { final Context context = getContext(); OnClickListener viewMoreListener = new OnClickListener() { @Override public void onClick(View view) { // TODO UriHandler.open(StringUtils.formatUs("path_to_url", user.getIdOrUid()), context); //context.startActivity(DiaryListActivity.makeIntent(mUser, context)); } }; mTitleText.setOnClickListener(viewMoreListener); mViewMoreText.setOnClickListener(viewMoreListener); int i = 0; for (final Diary diary : diaryList) { if (i >= DIARY_COUNT_MAX) { break; } if (i >= mDiaryList.getChildCount()) { LayoutInflater.from(context) .inflate(R.layout.profile_diary_item, mDiaryList); } View diaryLayout = mDiaryList.getChildAt(i); DiaryLayoutHolder holder = (DiaryLayoutHolder) diaryLayout.getTag(); if (holder == null) { holder = new DiaryLayoutHolder(diaryLayout); diaryLayout.setTag(holder); ViewUtils.setTextViewLinkClickable(holder.titleText); } if (!TextUtils.isEmpty(diary.cover)) { holder.coverImage.setVisibility(VISIBLE); ImageUtils.loadImage(holder.coverImage, diary.cover); } else { holder.coverImage.setVisibility(GONE); } holder.titleText.setText(diary.title); holder.abstractText.setText(diary.abstract_); diaryLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // TODO UriHandler.open(StringUtils.formatUs("path_to_url", diary.id), context); //context.startActivity(DiaryActivity.makeIntent(diary, context)); } }); ++i; } ViewUtils.setVisibleOrGone(mDiaryList, i != 0); ViewUtils.setVisibleOrGone(mEmptyView, i == 0); if (user.diaryCount > i) { mViewMoreText.setText(context.getString(R.string.view_more_with_count_format, user.diaryCount)); } else { mViewMoreText.setVisibility(GONE); } for (int count = mDiaryList.getChildCount(); i < count; ++i) { ViewUtils.setVisibleOrGone(mDiaryList.getChildAt(i), false); } } static class DiaryLayoutHolder { @BindView(R.id.cover) public ImageView coverImage; @BindView(R.id.title) public TextView titleText; @BindView(R.id.abstract_) public TextView abstractText; public DiaryLayoutHolder(View diaryLayout) { ButterKnife.bind(this, diaryLayout); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/ui/ProfileDiariesLayout.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
926
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.profile.content; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import java.util.Collections; import java.util.List; import me.zhanghai.android.douya.content.RawListResourceFragment; import me.zhanghai.android.douya.network.api.ApiError; import me.zhanghai.android.douya.network.api.ApiRequest; import me.zhanghai.android.douya.network.api.ApiService; import me.zhanghai.android.douya.network.api.info.frodo.UserItemList; import me.zhanghai.android.douya.network.api.info.frodo.UserItems; import me.zhanghai.android.douya.util.FragmentUtils; public class UserItemListResource extends RawListResourceFragment<UserItemList, UserItems> { private static final String KEY_PREFIX = UserItemListResource.class.getName() + '.'; private static final String EXTRA_USER_ID_OR_UID = KEY_PREFIX + "user_id_or_uid"; private String mUserIdOrUid; private static final String FRAGMENT_TAG_DEFAULT = UserItemListResource.class.getName(); private static UserItemListResource newInstance(String userIdOrUid) { //noinspection deprecation return new UserItemListResource().setArguments(userIdOrUid); } public static UserItemListResource attachTo(String userIdOrUid, Fragment fragment, String tag, int requestCode) { FragmentActivity activity = fragment.getActivity(); UserItemListResource instance = FragmentUtils.findByTag(activity, tag); if (instance == null) { instance = newInstance(userIdOrUid); FragmentUtils.add(instance, activity, tag); } instance.setTarget(fragment, requestCode); return instance; } public static UserItemListResource attachTo(String userIdOrUid, Fragment fragment) { return attachTo(userIdOrUid, fragment, FRAGMENT_TAG_DEFAULT, REQUEST_CODE_INVALID); } /** * @deprecated Use {@code attachTo()} instead. */ public UserItemListResource() {} protected UserItemListResource setArguments(String userIdOrUid) { FragmentUtils.getArgumentsBuilder(this) .putString(EXTRA_USER_ID_OR_UID, userIdOrUid); return this; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUserIdOrUid = getArguments().getString(EXTRA_USER_ID_OR_UID); } @Override protected ApiRequest<UserItemList> onCreateRequest() { return ApiService.getInstance().getUserItemList(mUserIdOrUid); } @Override protected void onLoadStarted() { getListener().onLoadUserItemListStarted(getRequestCode()); } @Override protected void onLoadFinished(boolean successful, UserItemList response, ApiError error) { onLoadFinished(successful, response != null ? response.list : null, error); } private void onLoadFinished(boolean successful, List<UserItems> response, ApiError error) { if (successful) { set(response); getListener().onLoadUserItemListFinished(getRequestCode()); getListener().onUserItemListChanged(getRequestCode(), Collections.unmodifiableList(response)); } else { getListener().onLoadUserItemListFinished(getRequestCode()); getListener().onLoadUserItemListError(getRequestCode(), error); } } private Listener getListener() { return (Listener) getTarget(); } public interface Listener { void onLoadUserItemListStarted(int requestCode); void onLoadUserItemListFinished(int requestCode); void onLoadUserItemListError(int requestCode, ApiError error); /** * @param newUserItemList Unmodifiable. */ void onUserItemListChanged(int requestCode, List<UserItems> newUserItemList); } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/profile/content/UserItemListResource.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
769
```java /* * All Rights Reserved. */ package me.zhanghai.android.douya.functional; import java.util.Iterator; import me.zhanghai.android.douya.functional.compat.Consumer; public class IteratorCompat { private IteratorCompat() {} public static <T> void forEachRemaining(Iterator<T> iterator, Consumer<T> consumer) { while (iterator.hasNext()) { T t = iterator.next(); consumer.accept(t); } } } ```
/content/code_sandbox/app/src/main/java/me/zhanghai/android/douya/functional/IteratorCompat.java
java
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
93