Thursday 5 October 2017

FlowLayoutDemo

1)package com.abc.utils;

import android.annotation.TargetApi;import android.content.Context;import android.content.res.TypedArray;import android.os.Build;import android.util.AttributeSet;import android.view.Gravity;import android.view.View;import android.view.ViewGroup;import com.theindianchanneltablet.R;import java.util.ArrayList;import java.util.List;

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class ABCFlowLayout extends ViewGroup {

    private int mGravity = (isIcs() ? Gravity.START : Gravity.LEFT) | Gravity.TOP;    private final List<List<View>> mLines = new ArrayList<List<View>>();    private final List<Integer> mLineHeights = new ArrayList<Integer>();    private final List<Integer> mLineMargins = new ArrayList<Integer>();
    public ABCFlowLayout(Context context) {
        this(context, null);    }
    public ABCFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);    }
    public ABCFlowLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs,                R.styleable.FlowLayout, defStyle, 0);        try {
            int index = a.getInt(R.styleable.FlowLayout_android_gravity, -1);            if (index > 0) {
                setGravity(index);            }
        } finally {
            a.recycle();        }

    }

    /**     * {@inheritDoc}     */    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        int width = 0;        int height = getPaddingTop() + getPaddingBottom();
        int lineWidth = 0;        int lineHeight = 0;
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {

            View child = getChildAt(i);            boolean lastChild = i == childCount - 1;
            if (child.getVisibility() == View.GONE) {

                if (lastChild) {
                    width = Math.max(width, lineWidth);                    height += lineHeight;                }

                continue;            }

            measureChildWithMargins(child, widthMeasureSpec, lineWidth, heightMeasureSpec, height);
            LayoutParams lp = (LayoutParams) child.getLayoutParams();
            int childWidthMode = MeasureSpec.AT_MOST;            int childWidthSize = sizeWidth;
            int childHeightMode = MeasureSpec.AT_MOST;            int childHeightSize = sizeHeight;
            if (lp.width == LayoutParams.MATCH_PARENT) {
                childWidthMode = MeasureSpec.EXACTLY;                childWidthSize -= lp.leftMargin + lp.rightMargin;            } else if (lp.width >= 0) {
                childWidthMode = MeasureSpec.EXACTLY;                childWidthSize = lp.width;            }

            if (lp.height >= 0) {
                childHeightMode = MeasureSpec.EXACTLY;                childHeightSize = lp.height;            } else if (modeHeight == MeasureSpec.UNSPECIFIED) {
                childHeightMode = MeasureSpec.UNSPECIFIED;                childHeightSize = 0;            }

            child.measure(
                    MeasureSpec.makeMeasureSpec(childWidthSize, childWidthMode),                    MeasureSpec.makeMeasureSpec(childHeightSize, childHeightMode)
            );
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            if (lineWidth + childWidth > sizeWidth) {

                width = Math.max(width, lineWidth);                lineWidth = childWidth;
                height += lineHeight;                lineHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
            } else {
                lineWidth += childWidth;                lineHeight = Math.max(lineHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);            }

            if (lastChild) {
                width = Math.max(width, lineWidth);                height += lineHeight;            }

        }

        width += getPaddingLeft() + getPaddingRight();
        setMeasuredDimension(
                (modeWidth == MeasureSpec.EXACTLY) ? sizeWidth : width,                (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight : height);    }

    /**     * {@inheritDoc}     */    @Override    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        mLines.clear();        mLineHeights.clear();        mLineMargins.clear();
        int width = getWidth();        int height = getHeight();
        int linesSum = getPaddingTop();
        int lineWidth = 0;        int lineHeight = 0;        List<View> lineViews = new ArrayList<View>();
        float horizontalGravityFactor;        switch ((mGravity & Gravity.HORIZONTAL_GRAVITY_MASK)) {
            case Gravity.LEFT:
            default:
                horizontalGravityFactor = 0;                break;            case Gravity.CENTER_HORIZONTAL:
                horizontalGravityFactor = .5f;                break;            case Gravity.RIGHT:
                horizontalGravityFactor = 1;                break;        }

        for (int i = 0; i < getChildCount(); i++) {

            View child = getChildAt(i);
            if (child.getVisibility() == View.GONE) {
                continue;            }

            LayoutParams lp = (LayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;            int childHeight = child.getMeasuredHeight() + lp.bottomMargin + lp.topMargin;
            if (lineWidth + childWidth > width) {
                mLineHeights.add(lineHeight);                mLines.add(lineViews);                mLineMargins.add((int) ((width - lineWidth) * horizontalGravityFactor) + getPaddingLeft());
                linesSum += lineHeight;
                lineHeight = 0;                lineWidth = 0;                lineViews = new ArrayList<View>();            }

            lineWidth += childWidth;            lineHeight = Math.max(lineHeight, childHeight);            lineViews.add(child);        }

        mLineHeights.add(lineHeight);        mLines.add(lineViews);        mLineMargins.add((int) ((width - lineWidth) * horizontalGravityFactor) + getPaddingLeft());
        linesSum += lineHeight;
        int verticalGravityMargin = 0;        switch ((mGravity & Gravity.VERTICAL_GRAVITY_MASK)) {
            case Gravity.TOP:
            default:
                break;            case Gravity.CENTER_VERTICAL:
                verticalGravityMargin = (height - linesSum) / 2;                break;            case Gravity.BOTTOM:
                verticalGravityMargin = height - linesSum;                break;        }

        int numLines = mLines.size();        int left;        int top = getPaddingTop();
        for (int i = 0; i < numLines; i++) {
            lineHeight = mLineHeights.get(i);            lineViews = mLines.get(i);            left = mLineMargins.get(i);
            int children = lineViews.size();            for (int j = 0; j < children; j++) {
                View child = lineViews.get(j);                if (child.getVisibility() == View.GONE) {
                    continue;                }

                LayoutParams lp = (LayoutParams) child.getLayoutParams();                // if height is match_parent we need to remeasure child to line height                if (lp.height == LayoutParams.MATCH_PARENT) {
                    int childWidthMode = MeasureSpec.AT_MOST;                    int childWidthSize = lineWidth;
                    if (lp.width == LayoutParams.MATCH_PARENT) {
                        childWidthMode = MeasureSpec.EXACTLY;                    } else if (lp.width >= 0) {
                        childWidthMode = MeasureSpec.EXACTLY;                        childWidthSize = lp.width;                    }

                    child.measure(
                            MeasureSpec.makeMeasureSpec(childWidthSize, childWidthMode),                            MeasureSpec.makeMeasureSpec(lineHeight - lp.topMargin - lp.bottomMargin, MeasureSpec.EXACTLY)
                    );                }

                int childWidth = child.getMeasuredWidth();                int childHeight = child.getMeasuredHeight();
                int gravityMargin = 0;
                if (Gravity.isVertical(lp.gravity)) {
                    switch (lp.gravity) {
                        case Gravity.TOP:
                        default:
                            break;                        case Gravity.CENTER_VERTICAL:
                        case Gravity.CENTER:
                            gravityMargin = (lineHeight - childHeight - lp.topMargin - lp.bottomMargin) / 2;                            break;                        case Gravity.BOTTOM:
                            gravityMargin = lineHeight - childHeight - lp.topMargin - lp.bottomMargin;                            break;                    }
                }

                child.layout(left + lp.leftMargin,                        top + lp.topMargin + gravityMargin + verticalGravityMargin,                        left + childWidth + lp.leftMargin,                        top + childHeight + lp.topMargin + gravityMargin + verticalGravityMargin);
                left += childWidth + lp.leftMargin + lp.rightMargin;
            }

            top += lineHeight;        }

    }

    @Override    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        return new LayoutParams(p);    }

    /**     * {@inheritDoc}     */    @Override    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);    }

    /**     * {@inheritDoc}     */    @Override    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void setGravity(int gravity) {
        if (mGravity != gravity) {
            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
                gravity |= isIcs() ? Gravity.START : Gravity.LEFT;            }

            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
                gravity |= Gravity.TOP;            }

            mGravity = gravity;            requestLayout();        }
    }

    public int getGravity() {
        return mGravity;    }


    /**     * @return <code>true</code> if device is running ICS or grater version of Android.     */    private static boolean isIcs() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;    }

    public void setOrientation(int or) {
        //setOrientation(or);
    }

    public static class LayoutParams extends MarginLayoutParams {

        public int gravity = -1;
        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.FlowLayout_Layout);
            try {
                gravity = a.getInt(R.styleable.FlowLayout_Layout_android_layout_gravity, -1);            } finally {
                a.recycle();            }
        }

        public LayoutParams(int width, int height) {
            super(width, height);        }

        public LayoutParams(ViewGroup.LayoutParams source) {
            super(source);        }
    }
}

<com.abc.utils.FlowLayout    android:id="@+id/act_remark_flow_layout_type"    android:layout_width="match_parent"    android:layout_height="wrap_content">
</com.abc.utils.FlowLayout>
public static String getRadioButtonValue(ABCFlowLayout view) {
    ABCFlowLayout innerView = (ABCFlowLayout) view;    for (int j = 0; j < innerView.getChildCount(); j++) {
        View rBtnView = innerView.getChildAt(j);        if (rBtnView instanceof RadioButton) {
            final RadioButton rBtn = (RadioButton) rBtnView;            if (rBtn.isChecked()) {
                return rBtn.getText().toString();            }
        }
    }
    return "";}

public static void setSingleRadioButton(ABCFlowLayout view, View v) {
    RadioButton rBtnSelected = (RadioButton) v;    ABCFlowLayout innerView = (ABCFlowLayout) view;
    for (int j = 0; j < innerView.getChildCount(); j++) {
        View rBtnView = innerView.getChildAt(j);        if (rBtnView instanceof RadioButton) {
            final RadioButton rBtn = (RadioButton) rBtnView;            rBtn.setChecked(false);        }
    }
    rBtnSelected.setChecked(true);}

public static ABCFlowLayout.LayoutParams setFlowLayoutOrientation(Activity activity) {
    int TAG_MARGIN = (int) activity.getResources().getDimension(R.dimen.margin_5dp);    ABCFlowLayout.LayoutParams paramsTag = new KcsFlowLayout.LayoutParams(ABCFlowLayout.LayoutParams.WRAP_CONTENT, ABCFlowLayout.LayoutParams.WRAP_CONTENT);    paramsTag.setMargins(TAG_MARGIN, TAG_MARGIN, 0, 0);    return paramsTag;}
2)AdapterCustomSpinner
package com.binarysignals.adapter;
import android.app.Activity;import android.content.Context;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.Filter;import android.widget.Filterable;import android.widget.TextView;
import com.binarysignals.R;import com.binarysignals.model.ModelCountryList;
import java.util.ArrayList;import java.util.List;
/** * Created by Priyank Prajapati on 4/29/2017. */public class AdapterCustomSpinner extends ArrayAdapter implements Filterable {
    private Activity activity;    private List<ModelCountryList> mDataList;    ArrayList<ModelCountryList> suggestion;    LayoutInflater inflater;    boolean mIsCountry = false;    private Filter filter = new CustomFilter();
    public AdapterCustomSpinner(Activity activitySpinner, int textViewResourceId, List<ModelCountryList> mList, boolean isCountry) {
        super(activitySpinner, textViewResourceId, mList);        activity = activitySpinner;        mDataList = mList;        suggestion = new ArrayList<>(mList);        mIsCountry = isCountry;        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    }

    @NonNull    @Override    public Filter getFilter() {
        return filter;    }

    public ModelCountryList getModel(int i) {
        return suggestion.get(i);    }

    @Nullable    @Override    public ModelCountryList getItem(int position) {
        return suggestion.get(position);    }

    @Override    public int getCount() {
        return suggestion.size();    }

    @NonNull    @Override    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/        View rowview = inflater.inflate(R.layout.row_spinner, parent, false);
        /***** Get each Model object from Arraylist ********/        TextView txtTitle = (TextView) rowview.findViewById(R.id.rowTxtSpinner);        if (mIsCountry) {
            // ** for country Name **            txtTitle.setText(suggestion.get(position).getName());        } else {
            // ** for country Code **            txtTitle.setText(suggestion.get(position).getCountry_code());        }

        return rowview;    }

    /**     * Our Custom Filter Class.     */    private class CustomFilter extends Filter {
        @Override        protected FilterResults performFiltering(CharSequence constraint) {
            suggestion.clear();
            if (mDataList != null && constraint != null) { // Check if the Original List and Constraint aren't null.                constraint = constraint.toString().toLowerCase();                for (int i = 0; i < mDataList.size(); i++) {
                    if (mDataList.get(i).getName().toLowerCase().contains(constraint) ||
                            mDataList.get(i).getCountry_code().toLowerCase().contains(constraint)) { // Compare item in original list if it contains constraints.                        suggestion.add(mDataList.get(i)); // If TRUE add item in Suggestions.                    }
                }
            }
            FilterResults results = new FilterResults(); // Create new Filter Results and return this to publishResults;            results.values = suggestion;            results.count = suggestion.size();
            return results;        }

        @Override        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (results.count > 0) {
                notifyDataSetChanged();            } else {
                notifyDataSetInvalidated();            }
        }
    }
}
<android.support.design.widget.TextInputLayout    android:id="@+id/my_account_spn_country_inputlyt"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:textColorHint="@color/color_text_spnr"    android:layout_marginTop="@dimen/margin_10dp"    android:visibility="gone">
    <com.app.utils.InstantAutoComplete        android:id="@+id/my_account_spn_country"        style="@style/topuptextboxstyle"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="@string/topupaccount_selectyourcountry"        android:imeOptions="actionNext"        android:maxLines="1"        android:singleLine="true"        android:text="@{accountModel.country}" /></android.support.design.widget.TextInputLayout>

3)package com.app.utils;

import android.content.Context;import android.graphics.Rect;import android.graphics.drawable.Drawable;import android.support.v4.content.ContextCompat;import android.support.v7.widget.AppCompatAutoCompleteTextView;import android.text.InputType;import android.util.AttributeSet;import android.view.View;


public class InstantAutoComplete extends AppCompatAutoCompleteTextView {

    private boolean showAlways;    private Context mContext;
    public InstantAutoComplete(Context context) {
        super(context);        mContext = context;        loadDefaultSetting(context);
    }

    private void loadDefaultSetting(Context context) {
        //setCursorVisible(false);        setHintTextColor(ContextCompat.getColor(mContext, R.color.autocomplete_hint_color));        setAllCaps(false);        Drawable img = ContextCompat.getDrawable(context, R.drawable.downarw);        setCompoundDrawablesWithIntrinsicBounds(null, null, img, null);        setCompoundDrawablePadding(5);        //setFocusable(false);        //setFocusableInTouchMode(false);    }

    public void setEditableMode(boolean isEditable) {
        setFocusable(isEditable);        setFocusableInTouchMode(isEditable);        if (isEditable) {
            setInputType(InputType.TYPE_CLASS_TEXT);            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);        } else {
            setInputType(InputType.TYPE_NULL);            loadDefaultSetting(mContext);        }

    }

    public InstantAutoComplete(Context context, AttributeSet attrs) {
        super(context, attrs);        mContext = context;        loadDefaultSetting(context);    }

    public InstantAutoComplete(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);        mContext = context;        loadDefaultSetting(context);    }


    public void setShowAlways(boolean showAlways) {
        this.showAlways = showAlways;    }

    @Override    public boolean enoughToFilter() {
        return showAlways || super.enoughToFilter();    }

    @Override    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        showDropDownIfFocused();    }

    private void showDropDownIfFocused() {
        if (enoughToFilter() && isFocused() && getWindowVisibility() == View.VISIBLE) {

            showDropDown();        }
    }

    @Override    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        showDropDownIfFocused();    }

}

if (mCountryList != null && mCountryList.size() > 0) {
    mCountryAdapter = new AdapterCustomSpinner(getActivity(), R.layout.row_spinner,            mCountryList, true);    mBinding.myAccountSpnCountry.setAdapter(mCountryAdapter);    mBinding.myAccountSpnCountry.setThreshold(0);    mBinding.myAccountSpnCountry.showDropDown();}