How to change color in ExpandableRecyclerView - android

I am using this library but I can't get to a way to change the group background color from white.
EDIT: the xml files as requested in comments:
content_main.xml
the content_main file which include the expandable recyclerview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false" />
</LinearLayout>
activity_main.xml
the main activity
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#64dd17"
tools:context="ayalma.ir.sample.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
row_drawer.xml
the custom row layout
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#ffb74d">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="#dimen/carbon_toolbarHeight"
android:gravity="center_vertical"
android:paddingLeft="#dimen/carbon_padding"
android:paddingRight="#dimen/carbon_padding" />
</LinearLayout>

Add this line to your
<ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
tools:listitem="#layout/exr_group"
And change backgound color

Remove your previous library from Gradle
compile 'com.github.ayalma:ExpandableRecyclerView:0.2.0'
Add this library to your Gradle
compile 'com.nineoldandroids:library:2.4.0'
Copy this file to your package
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;
public class ExpandableRecyclerView extends android.support.v7.widget.RecyclerView {
public ExpandableRecyclerView(Context context) {
super(context, null);
initRecycler();
}
public ExpandableRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
initRecycler();
}
public ExpandableRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initRecycler();
}
private void initRecycler() {
setClipToPadding(false);
setItemAnimator(new DefaultItemAnimator());
}
#Override
public Parcelable onSaveInstanceState() {
//begin boilerplate code that allows parent classes to save state
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
//end
if (getAdapter() != null)
ss.stateToSave = ((Adapter) this.getAdapter()).getExpandedGroups();
return ss;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
//begin boilerplate code so parent classes can restore state
if (!(state instanceof SavedState)) // if state is not instance of out SaveState just restore in reg way
{
super.onRestoreInstanceState(state);
return;
}
// else if cast him to SavedState
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
//end
if (getAdapter() != null)
((Adapter) getAdapter()).setExpandedGroups(ss.stateToSave);
}
static class SavedState implements Parcelable {
public static final SavedState EMPTY_STATE = new SavedState() {
};
SparseBooleanArray stateToSave;
Parcelable superState;
SavedState() {
superState = null;
}
SavedState(Parcelable superState) {
this.superState = superState != EMPTY_STATE ? superState : null;
}
private SavedState(Parcel in) {
Parcelable superState = in.readParcelable(ExpandableRecyclerView.class.getClassLoader());
this.superState = superState != null ? superState : EMPTY_STATE;
this.stateToSave = in.readSparseBooleanArray();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(#NonNull Parcel out, int flags) {
out.writeParcelable(superState, flags);
out.writeSparseBooleanArray(this.stateToSave);
}
public Parcelable getSuperState() {
return superState;
}
//required field that makes Parcelables from a Parcel
public static final Creator<SavedState> CREATOR =
new Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
#Override
public void setAdapter(android.support.v7.widget.RecyclerView.Adapter adapter) {
if (!(adapter instanceof Adapter))
throw new IllegalArgumentException("adapter has to be of type ExpandableRecyclerView.Adapter");
super.setAdapter(adapter);
}
public static abstract class Adapter<CVH extends ViewHolder, GVH extends ViewHolder, C, G> extends RecyclerView.Adapter<ViewHolder> {
private OnChildItemClickedListener onChildItemClickedListener;
private static final int TYPE_HEADER = 0;
SparseBooleanArray expanded = new SparseBooleanArray();
public Adapter() {
}
boolean isExpanded(int group) {
return expanded.get(group);
}
SparseBooleanArray getExpandedGroups() {
return expanded;
}
public void setExpandedGroups(SparseBooleanArray expanded) {
this.expanded = expanded;
}
public void expand(int group) {
if (isExpanded(group))
return;
// this lines of code calculate number of shown item in recycler view. also group is counting .
int position = 0;
for (int i = 0; i < group; i++) {
position++;
if (isExpanded(i))
position += getChildItemCount(i);
}
position++; // this for percent group
notifyItemRangeInserted(position, getChildItemCount(group)); // notify recycler view for expanding
expanded.put(group, true); // save expanding in sparce array
}
public void collapse(int group) {
if (!isExpanded(group)) // if is not expanded . so nothing to collapse.
return;
int position = 0;
for (int i = 0; i < group; i++) {
position++;
if (isExpanded(i))
position += getChildItemCount(i); // item
}
position++;
notifyItemRangeRemoved(position, getChildItemCount(group));
expanded.put(group, false);
}
public abstract int getGroupItemCount();
public abstract int getChildItemCount(int group);
#Override
public int getItemCount() {
int count = 0;
for (int i = 0; i <= getGroupItemCount(); i++) {
count += isExpanded(i) ? getChildItemCount(i) + 1 : 1;
}
return count;
}
public abstract G getGroupItem(int position);
public abstract C getChildItem(int group, int position);
public Object getItem(int i) {
int group = 0;
while (group <= getGroupItemCount()) {
if (i > 0 && !isExpanded(group)) {
i--;
group++;
continue;
}
if (i > 0 && isExpanded(group)) {
i--;
if (i < getChildItemCount(group))
return getChildItem(group, i);
i -= getChildItemCount(group);
group++;
continue;
}
if (i == 0)
return getGroupItem(group);
}
throw new IndexOutOfBoundsException();
}
#Override
public void onBindViewHolder(ViewHolder holder, int i) {
int group = 0;
while (group <= getGroupItemCount()) {
if (i > 0 && !isExpanded(group)) {
i--;
group++;
continue;
}
if (i > 0 && isExpanded(group)) {
i--;
if (i < getChildItemCount(group)) {
onBindChildViewHolder((CVH) holder, group, i);
return;
}
i -= getChildItemCount(group);
group++;
continue;
}
if (i == 0) {
onBindGroupViewHolder((GVH) holder, group);
return;
}
}
throw new IndexOutOfBoundsException();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return viewType == TYPE_HEADER ? onCreateGroupViewHolder(parent) : onCreateChildViewHolder(parent, viewType);
}
protected abstract GVH onCreateGroupViewHolder(ViewGroup parent);
protected abstract CVH onCreateChildViewHolder(ViewGroup parent, int viewType);
public abstract int getChildItemViewType(int group, int position);
#Override
public int getItemViewType(int i) {
int group = 0;
while (group <= getGroupItemCount()) {
if (i > 0 && !isExpanded(group)) {
i--;
group++;
continue;
}
if (i > 0 && isExpanded(group)) {
i--;
if (i < getChildItemCount(group))
return getChildItemViewType(group, i);
i -= getChildItemCount(group);
group++;
continue;
}
if (i == 0)
return TYPE_HEADER;
}
throw new IndexOutOfBoundsException();
}
public void setOnChildItemClickedListener(OnChildItemClickedListener onItemClickedListener) {
this.onChildItemClickedListener = onItemClickedListener;
}
public void onBindChildViewHolder(CVH holder, final int group, final int position) {
holder.itemView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (Adapter.this.onChildItemClickedListener != null) {
Adapter.this.onChildItemClickedListener.onChildItemClicked(group, position);
}
}
});
}
public void onBindGroupViewHolder(final GVH holder, final int group) {
if (holder instanceof GroupViewHolder)
((GroupViewHolder) holder).setExpanded(isExpanded(group));
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (isExpanded(group)) {
collapse(group);
if (holder instanceof GroupViewHolder)
((GroupViewHolder) holder).collapse();
} else {
expand(group);
if (holder instanceof GroupViewHolder)
((GroupViewHolder) holder).expand();
}
}
});
}
}
public static abstract class GroupViewHolder extends RecyclerView.ViewHolder {
public GroupViewHolder(View itemView) {
super(itemView);
}
public abstract void expand();
public abstract void collapse();
public abstract void setExpanded(boolean expanded);
public abstract boolean isExpanded();
}
public static class SimpleGroupViewHolder extends GroupViewHolder {
ImageView expandedIndicator;
TextView text;
private boolean expanded;
public SimpleGroupViewHolder(Context context) {
super(View.inflate(context, R.layout.exr_group, null));
itemView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
expandedIndicator = (ImageView) itemView.findViewById(R.id.carbon_groupExpandedIndicator);
text = (TextView) itemView.findViewById(R.id.carbon_groupText);
}
public void expand() {
ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
expandedIndicator.postInvalidate();
}
});
animator.start();
expanded = true;
}
public void collapse() {
ValueAnimator animator = ValueAnimator.ofFloat(1, 0);
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
expandedIndicator.postInvalidate();
}
});
animator.start();
expanded = false;
}
public void setExpanded(boolean expanded) {
ViewHelper.setRotation(expandedIndicator, expanded ? 180 : 0);
this.expanded = expanded;
}
#Override
public boolean isExpanded() {
return expanded;
}
public void setText(String t) {
text.setText(t);
}
public String getText() {
return text.getText().toString();
}
}
public interface OnChildItemClickedListener {
void onChildItemClicked(int group, int position);
}
}
group xml copy to layout folder
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fefefe"
android:clickable="true"
android:orientation="horizontal">
<TextView
android:id="#+id/carbon_groupText"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_weight="1"
android:gravity="center_vertical" />
<ImageView
android:id="#+id/carbon_groupExpandedIndicator"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center_vertical"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:tint="#000000"
app:srcCompat="#drawable/ic_expand_more_24dp" />
</LinearLayout>
copy inside drawable folder
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M16.59,8.59L12,13.17 7.41,8.59 6,10l6,6 6,-6z"/>
</vector>
Now user this inside your xml
<com.example.package.ExpandableRecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false" />
instead of
<ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false" />

Related

How to programmatically reMeasure view?

I have CustomView with 2 RelativeLayouts. There are RecyclerViews in each RelativeLayout. When I add new element to RecyclerView it doesn`t change height.
If I change screen orientation then android measures it well. So my question is how to programmatically tell android that he needs remeasure both childs and parent elements.
requestlayout() and invalidate() doesn`t work
CustomView:
public class ExpandableView extends LinearLayout {
private Settings mSettings ;
private int mExpandState;
private ValueAnimator mExpandAnimator;
private ValueAnimator mParentAnimator;
private AnimatorSet mExpandScrollAnimatorSet;
private int mExpandedViewHeight;
private boolean mIsInit = true;
private int defaultHeight;
private boolean isAllowedExpand = false;
private ScrolledParent mScrolledParent;
private OnExpandListener mOnExpandListener;
public ExpandableView(Context context) {
super(context);
init(null);
}
public ExpandableView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public ExpandableView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void init(AttributeSet attrs) {
Log.w("tag", "init");
setOrientation(VERTICAL);
this.setClipChildren(false);
this.setClipToPadding(false);
mExpandState = ExpandState.PRE_INIT;
mSettings = new Settings();
if(attrs!=null) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ExpandableView);
mSettings.expandDuration = typedArray.getInt(R.styleable.ExpandableView_expDuration, Settings.EXPAND_DURATION);
mSettings.expandWithParentScroll = typedArray.getBoolean(R.styleable.ExpandableView_expWithParentScroll,false);
mSettings.expandScrollTogether = typedArray.getBoolean(R.styleable.ExpandableView_expExpandScrollTogether,true);
typedArray.recycle();
}
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.w("tag", "onMeasure");
Log.w("tag", "widthMeasureSpec - " + widthMeasureSpec);
Log.w("tag", "heightMeasureSpec - " + heightMeasureSpec);
int childCount = getChildCount();
if(childCount!=2) {
throw new IllegalStateException("ExpandableLayout must has two child view !");
}
if(mIsInit) {
((MarginLayoutParams)getChildAt(0).getLayoutParams()).bottomMargin=0;
MarginLayoutParams marginLayoutParams = ((MarginLayoutParams)getChildAt(1).getLayoutParams());
marginLayoutParams.bottomMargin=0;
marginLayoutParams.topMargin=0;
marginLayoutParams.height = 0;
mExpandedViewHeight = getChildAt(1).getMeasuredHeight();
defaultHeight = mExpandedViewHeight;
mIsInit =false;
mExpandState = ExpandState.CLOSED;
View view = getChildAt(0);
if (view != null){
view.setOnClickListener(v -> toggle());
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Log.w("tag", "onSizeChanged");
if(mSettings.expandWithParentScroll) {
mScrolledParent = Utils.getScrolledParent(this);
}
}
private int getParentScrollDistance () {
int distance = 0;
Log.w("tag", "getParentScrollDistance");
if(mScrolledParent == null) {
return distance;
}
distance = (int) (getY() + getMeasuredHeight() + mExpandedViewHeight - mScrolledParent.scrolledView.getMeasuredHeight());
for(int index = 0; index < mScrolledParent.childBetweenParentCount; index++) {
ViewGroup parent = (ViewGroup) getParent();
distance+=parent.getY();
}
return distance;
}
private void verticalAnimate(final int startHeight, final int endHeight ) {
int distance = getParentScrollDistance();
final View target = getChildAt(1);
mExpandAnimator = ValueAnimator.ofInt(startHeight,endHeight);
mExpandAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
target.getLayoutParams().height = (int) animation.getAnimatedValue();
target.requestLayout();
}
});
mExpandAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if(endHeight-startHeight < 0) {
mExpandState = ExpandState.CLOSED;
if (mOnExpandListener != null) {
mOnExpandListener.onExpand(false);
}
} else {
mExpandState=ExpandState.EXPANDED;
if(mOnExpandListener != null) {
mOnExpandListener.onExpand(true);
}
}
}
});
mExpandState=mExpandState==ExpandState.EXPANDED?ExpandState.CLOSING :ExpandState.EXPANDING;
mExpandAnimator.setDuration(mSettings.expandDuration);
if(mExpandState == ExpandState.EXPANDING && mSettings.expandWithParentScroll && distance > 0) {
mParentAnimator = Utils.createParentAnimator(mScrolledParent.scrolledView, distance, mSettings.expandDuration);
mExpandScrollAnimatorSet = new AnimatorSet();
if(mSettings.expandScrollTogether) {
mExpandScrollAnimatorSet.playTogether(mExpandAnimator,mParentAnimator);
} else {
mExpandScrollAnimatorSet.playSequentially(mExpandAnimator,mParentAnimator);
}
mExpandScrollAnimatorSet.start();
} else {
mExpandAnimator.start();
}
}
public void setExpand(boolean expand) {
if (mExpandState == ExpandState.PRE_INIT) {return;}
getChildAt(1).getLayoutParams().height = expand ? mExpandedViewHeight : 0;
requestLayout();
mExpandState=expand?ExpandState.EXPANDED:ExpandState.CLOSED;
}
public boolean isExpanded() {
return mExpandState==ExpandState.EXPANDED;
}
public void toggle() {
if (isAllowedExpand){
if(mExpandState==ExpandState.EXPANDED) {
close();
}else if(mExpandState==ExpandState.CLOSED) {
expand();
}
}
}
public void expand() {
verticalAnimate(0,mExpandedViewHeight);
}
public void close() {
verticalAnimate(mExpandedViewHeight,0);
}
public interface OnExpandListener {
void onExpand(boolean expanded) ;
}
public void setOnExpandListener(OnExpandListener onExpandListener) {
this.mOnExpandListener = onExpandListener;
}
public void setExpandScrollTogether(boolean expandScrollTogether) {
this.mSettings.expandScrollTogether = expandScrollTogether;
}
public void setExpandWithParentScroll(boolean expandWithParentScroll) {
this.mSettings.expandWithParentScroll = expandWithParentScroll;
}
public void setExpandDuration(int expandDuration) {
this.mSettings.expandDuration = expandDuration;
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
Log.w("tag", "onDetachedFromWindow");
if(mExpandAnimator!=null&&mExpandAnimator.isRunning()) {
mExpandAnimator.cancel();
mExpandAnimator.removeAllUpdateListeners();
}
if(mParentAnimator!=null&&mParentAnimator.isRunning()) {
mParentAnimator.cancel();
mParentAnimator.removeAllUpdateListeners();
}
if(mExpandScrollAnimatorSet!=null) {
mExpandScrollAnimatorSet.cancel();
}
}
public void setAllowedExpand(boolean allowedExpand) {
isAllowedExpand = allowedExpand;
}
public void increaseDistance(int size){
if(mExpandState==ExpandState.EXPANDED) {
close();
}
mExpandedViewHeight = defaultHeight + size;
}
//func just for loggs
public void showParams(){
RelativeLayout relativeLayout = (RelativeLayout) getChildAt(1);
/*relativeLayout.requestLayout();
relativeLayout.invalidate();*/
RecyclerView recyclerView = (RecyclerView) relativeLayout.getChildAt(1);
Log.d("tag", "height - " + relativeLayout.getHeight());
Log.d("tag", "childs - " + relativeLayout.getChildCount());
Log.d("tag", "recycler height - " + recyclerView.getHeight());
recyclerView.requestLayout();
recyclerView.invalidateItemDecorations();
recyclerView.invalidate();
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
layoutManager.getHeight();
Log.d("tag", " layoutManager.getHeight() - " + layoutManager.getHeight());
layoutManager.requestLayout();
layoutManager.generateDefaultLayoutParams();
layoutManager.onItemsChanged(recyclerView);
Log.d("tag", " layoutManager.getHeight()2- " + layoutManager.getHeight());
layoutManager.getChildCount();
recyclerView.getChildCount();
Log.d("tag", "manager childs - " + layoutManager.getChildCount());
Log.d("tag", "recycler childs - " + recyclerView.getChildCount());
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/grey_light_color"
>
<com.example.develop.project.Utils.ExpandableView.ExpandableView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/test_custom_view"
app:expWithParentScroll="true"
android:layout_gravity="center"
android:background="#color/grey_color"
>
<android.support.v7.widget.CardView
android:id="#+id/start_card"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#color/white_color"
android:layout_marginTop="5dp"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/stage_tv4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/grey_deep_color"
android:text="Запуск"
android:layout_centerVertical="true"
android:layout_marginStart="15dp"
android:textSize="18sp"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/start_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start_accept"
android:textSize="18sp"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:textColor="#color/grey_deep_color"
android:layout_marginEnd="15dp"
/>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_test_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/start_tv"
android:layout_marginTop="10dp"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
</com.example.develop.project.Utils.ExpandableView.ExpandableView>
<Button
android:id="#+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:text="Add elem"
android:layout_marginStart="15dp"
android:layout_marginBottom="15dp"
/>
<Button
android:id="#+id/check_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="Check params"
android:layout_marginBottom="15dp"
android:layout_marginEnd="15dp"
/>
</RelativeLayout>
Activity:
public class TestActivity extends MvpAppCompatActivity implements TestContract.View {
TestAdapter testAdapter;
#InjectPresenter
public TestPresenter presenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
init();
}
private void init() {
ExpandableView expandableView = findViewById(R.id.test_custom_view);
expandableView.setAllowedExpand(true);
Button add_btn = findViewById(R.id.add_btn);
Button check_btn = findViewById(R.id.check_btn);
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
presenter.addElem();
}
});
check_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
expandableView.showParams();
}
});
}
#Override
public void addElems(ArrayList<String> list) {
testAdapter.notifyDataSetChanged();
}
#Override
public void populateAdapter(ArrayList<String> list) {
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
RecyclerView recyclerView = findViewById(R.id.my_test_tv);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(false);
testAdapter = new TestAdapter(list);
recyclerView.setAdapter(testAdapter);
}
}
Adapter:
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.TasksViewHolder> {
private List<String> list;
public TestAdapter(List<String> list) {
this.list = list;
}
#NonNull
#Override
public TestAdapter.TasksViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.test_item, parent, false);
TestAdapter.TasksViewHolder vh = new TestAdapter.TasksViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull TestAdapter.TasksViewHolder holder, int position) {
String text = list.get(position);
holder.textView.setText(text);
}
public static class TasksViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public TasksViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.my_test_tv);
}
}
#Override
public int getItemCount() {
return list.size();
}
}
The ExpandableView contains some suspicious code in its onMeasure method.
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
...
if(mIsInit) {
((MarginLayoutParams)getChildAt(0).getLayoutParams()).bottomMargin=0;
MarginLayoutParams marginLayoutParams = ((MarginLayoutParams)getChildAt(1).getLayoutParams());
marginLayoutParams.bottomMargin=0;
marginLayoutParams.topMargin=0;
marginLayoutParams.height = 0;
mExpandedViewHeight = getChildAt(1).getMeasuredHeight();
defaultHeight = mExpandedViewHeight;
mIsInit =false;
mExpandState = ExpandState.CLOSED;
View view = getChildAt(0);
if (view != null){
view.setOnClickListener(v -> toggle());
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
The mIsInit variable is set to true on creation and than to false when onMeasure is called for the first time. So the code in the condition runs only once.
But it stores value mExpandedViewHeight obtained as getChildAt(1).getMeasuredHeight() and that is current height of your relative layout, which contains (still empty) RecyclerView.
As far as I can see there's nothing in ExpadableView's code that would update this value, when you add an item to the Recylerview.
I am not sure, what would the correct/perfect implementation of the onMeasure method be (for your component). That would require some debugging and testing of the component, and perhaps some tweaks in other parts of the code.
If you wrote the component, you may want to invest more effort into debugging. If you didn't write the component, you should try to find other one, that is properly implemented. Custom components with custom measurements are an advanced topic.
If you really want to go with debugging and fixing your component, that first thing to do is to update the mExpandedViewHeight value on every measurement, but that might require updating other values that are derived from this value.

Expandable RecycleView header and adapter

I am using this library to make a expandable RecyclerView
I made my own version of it so I can define the header but It's giving me I think I made something wrong because It's giving me this error.
What I want is:
a way to make my own header layout.
Is there a way to populate the adapter of the RecyclerView so that I don't have to create a new adapter file every time I want to implement the RecyclerView.
How to set my one item or more to be expanded as I open the activity.
My version of ExpandableRecyclerView:
public class ExpandableRecyclerView extends RecyclerView {
public ExpandableRecyclerView(Context context) {
super(context, null);
initRecycler();
}
public ExpandableRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
initRecycler();
}
public ExpandableRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initRecycler();
}
private void initRecycler() {
setClipToPadding(false);
setItemAnimator(new DefaultItemAnimator());
}
#Override
public Parcelable onSaveInstanceState() {
//begin boilerplate code that allows parent classes to save state
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
//end
if (getAdapter() != null)
ss.stateToSave = ((Adapter) this.getAdapter()).getExpandedGroups();
return ss;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
//begin boilerplate code so parent classes can restore state
if (!(state instanceof SavedState)) // if state is not instance of out SaveState just restore in reg way
{
super.onRestoreInstanceState(state);
return;
}
// else if cast him to SavedState
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
//end
if (getAdapter() != null)
((Adapter) getAdapter()).setExpandedGroups(ss.stateToSave);
}
#Override
public void setAdapter(RecyclerView.Adapter adapter) {
if (!(adapter instanceof Adapter))
throw new IllegalArgumentException("adapter has to be of type ExpandableRecyclerView.Adapter");
super.setAdapter(adapter);
}
public interface OnChildItemClickedListener {
void onChildItemClicked(int group, int position);
}
static class SavedState implements Parcelable {
public static final SavedState EMPTY_STATE = new SavedState() {
};
//required field that makes Parcelables from a Parcel
public static final Creator<SavedState> CREATOR =
new Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
SparseBooleanArray stateToSave;
Parcelable superState;
SavedState() {
superState = null;
}
SavedState(Parcelable superState) {
this.superState = superState != EMPTY_STATE ? superState : null;
}
private SavedState(Parcel in) {
Parcelable superState = in.readParcelable(ExpandableRecyclerView.class.getClassLoader());
this.superState = superState != null ? superState : EMPTY_STATE;
this.stateToSave = in.readSparseBooleanArray();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(#NonNull Parcel out, int flags) {
out.writeParcelable(superState, flags);
out.writeSparseBooleanArray(this.stateToSave);
}
public Parcelable getSuperState() {
return superState;
}
}
public static abstract class Adapter<CVH extends ViewHolder, GVH extends ViewHolder, C, G> extends RecyclerView.Adapter<ViewHolder> {
private static final int TYPE_HEADER = 0;
SparseBooleanArray expanded = new SparseBooleanArray();
private OnChildItemClickedListener onChildItemClickedListener;
public Adapter() {
}
boolean isExpanded(int group) {
return expanded.get(group);
}
SparseBooleanArray getExpandedGroups() {
return expanded;
}
public void setExpandedGroups(SparseBooleanArray expanded) {
this.expanded = expanded;
}
public void expand(int group) {
if (isExpanded(group))
return;
// this lines of code calculate number of shown item in recycler view. also group is counting .
int position = 0;
for (int i = 0; i < group; i++) {
position++;
if (isExpanded(i))
position += getChildItemCount(i);
}
position++; // this for percent group
notifyItemRangeInserted(position, getChildItemCount(group)); // notify recycler view for expanding
expanded.put(group, true); // save expanding in sparce array
}
public void collapse(int group) {
if (!isExpanded(group)) // if is not expanded . so nothing to collapse.
return;
int position = 0;
for (int i = 0; i < group; i++) {
position++;
if (isExpanded(i))
position += getChildItemCount(i); // item
}
position++;
notifyItemRangeRemoved(position, getChildItemCount(group));
expanded.put(group, false);
}
public abstract int getGroupItemCount();
public abstract int getChildItemCount(int group);
#Override
public int getItemCount() {
int count = 0;
for (int i = 0; i <= getGroupItemCount(); i++) {
count += isExpanded(i) ? getChildItemCount(i) + 1 : 1;
}
return count;
}
public abstract G getGroupItem(int position);
public abstract C getChildItem(int group, int position);
public Object getItem(int i) {
int group = 0;
while (group <= getGroupItemCount()) {
if (i > 0 && !isExpanded(group)) {
i--;
group++;
continue;
}
if (i > 0 && isExpanded(group)) {
i--;
if (i < getChildItemCount(group))
return getChildItem(group, i);
i -= getChildItemCount(group);
group++;
continue;
}
if (i == 0)
return getGroupItem(group);
}
throw new IndexOutOfBoundsException();
}
#Override
public void onBindViewHolder(ViewHolder holder, int i) {
int group = 0;
while (group <= getGroupItemCount()) {
if (i > 0 && !isExpanded(group)) {
i--;
group++;
continue;
}
if (i > 0 && isExpanded(group)) {
i--;
if (i < getChildItemCount(group)) {
onBindChildViewHolder((CVH) holder, group, i);
return;
}
i -= getChildItemCount(group);
group++;
continue;
}
if (i == 0) {
onBindGroupViewHolder((GVH) holder, group);
return;
}
}
throw new IndexOutOfBoundsException();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return viewType == TYPE_HEADER ? onCreateGroupViewHolder(parent) : onCreateChildViewHolder(parent, viewType);
}
protected abstract GVH onCreateGroupViewHolder(ViewGroup parent);
protected abstract CVH onCreateChildViewHolder(ViewGroup parent, int viewType);
public abstract int getChildItemViewType(int group, int position);
#Override
public int getItemViewType(int i) {
int group = 0;
while (group <= getGroupItemCount()) {
if (i > 0 && !isExpanded(group)) {
i--;
group++;
continue;
}
if (i > 0 && isExpanded(group)) {
i--;
if (i < getChildItemCount(group))
return getChildItemViewType(group, i);
i -= getChildItemCount(group);
group++;
continue;
}
if (i == 0)
return TYPE_HEADER;
}
throw new IndexOutOfBoundsException();
}
public void setOnChildItemClickedListener(OnChildItemClickedListener onItemClickedListener) {
this.onChildItemClickedListener = onItemClickedListener;
}
public void onBindChildViewHolder(CVH holder, final int group, final int position) {
holder.itemView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (Adapter.this.onChildItemClickedListener != null) {
Adapter.this.onChildItemClickedListener.onChildItemClicked(group, position);
}
}
});
}
public void onBindGroupViewHolder(final GVH holder, final int group) {
if (holder instanceof GroupViewHolder)
((GroupViewHolder) holder).setExpanded(isExpanded(group));
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (isExpanded(group)) {
collapse(group);
if (holder instanceof GroupViewHolder)
((GroupViewHolder) holder).collapse();
} else {
expand(group);
if (holder instanceof GroupViewHolder)
((GroupViewHolder) holder).expand();
}
}
});
}
}
public static abstract class GroupViewHolder extends ViewHolder {
public GroupViewHolder(View itemView) {
super(itemView);
}
public abstract void expand();
public abstract void collapse();
public abstract boolean isExpanded();
public abstract void setExpanded(boolean expanded);
}
public static class SimpleGroupViewHolder extends GroupViewHolder {
ImageView expandedIndicator;
TextView text;
private boolean expanded;
public SimpleGroupViewHolder(Context context) {
super(View.inflate(context, R.layout.group_header, null));
itemView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
expandedIndicator = (ImageView) itemView.findViewById(R.id.carbon_groupExpandedIndicator);
text = (TextView) itemView.findViewById(R.id.carbon_groupText);
}
public SimpleGroupViewHolder(Context context, int layout) {
super(View.inflate(context, layout, null));
itemView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
expandedIndicator = (ImageView) itemView.findViewById(R.id.carbon_groupExpandedIndicator);
text = (TextView) itemView.findViewById(R.id.carbon_groupText);
}
public void expand() {
ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
expandedIndicator.postInvalidate();
}
});
animator.start();
expanded = true;
}
public void collapse() {
ValueAnimator animator = ValueAnimator.ofFloat(1, 0);
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
expandedIndicator.postInvalidate();
}
});
animator.start();
expanded = false;
}
#Override
public boolean isExpanded() {
return expanded;
}
public void setExpanded(boolean expanded) {
ViewHelper.setRotation(expandedIndicator, expanded ? 180 : 0);
this.expanded = expanded;
}
public String getText() {
return text.getText().toString();
}
public void setText(String t) {
text.setText(t);
}
}
}
I got an answer for these questions:
How to set my one item or more to be expanded as I open the activity.
before setting the adapter for the RecyclerView I used expand() method as the following:
RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
MyAdapter adapter = new MyAdapter(getContext(), R.layout.group_header);
adapter.expand(0); // 0 will expand the first Item.
rv.setAdapter(adapter);
a way to make my own header layout.
all you need to do is create your own group header as the following:
static class GroupViewHolder extends ExpandableRecyclerView.GroupViewHolder {
ImageView expandedIndicator;
TextView text1;
TextView text2;
private boolean expanded;
GroupViewHolder(Context context, int layout) {
super(View.inflate(context, layout, null));
itemView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
expandedIndicator = (ImageView) itemView.findViewById(R.id.groupExpandedIndicator);
text1 = (TextView) itemView.findViewById(R.id.text1);
text2 = (TextView) itemView.findViewById(R.id.text2);
}
public void expand() {
ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
expandedIndicator.postInvalidate();
}
});
animator.start();
expanded = true;
}
public void collapse() {
ValueAnimator animator = ValueAnimator.ofFloat(1, 0);
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
expandedIndicator.postInvalidate();
}
});
animator.start();
expanded = false;
}
#Override
public boolean isExpanded() {
return expanded;
}
public void setExpanded(boolean expanded) {
ViewHelper.setRotation(expandedIndicator, expanded ? 180 : 0);
this.expanded = expanded;
}
void setText1(String t) {
text1.setText(t);
}
void setText2(String t) {
text2.setText(t);
}
}

Implement an scroll to select an item ListView

I want to use an ListView where you scroll the list to select an item.
It should be like a Seekbar but the thumb should be fixed and you must use the bar to adjust it. One problem am facing is, I have no idea how this kind of widget is called, making it hard for me to search. So I made this image below to give you an better idea. And to be fair, I don't even know if this is the right title for this kind of feature.
I usually see this kind of interface in clock setting (see below image)
Reference scroll horizontal at https://stackoverflow.com/a/38411582/5887320 by use RecyclerView instead of ListView.
This is my customize code to get virtical scroll :
1.dimens.xml
<dimen name="item_dob_width">100dp</dimen>
<dimen name="item_dob_height">50dp</dimen>
2.recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:id="#+id/tv_year"
android:layout_width="#dimen/item_dob_width"
android:layout_height="#dimen/item_dob_height"
android:textColor="#android:color/white"
android:background="#android:color/darker_gray"
android:textSize="28sp"
android:gravity="center"/>
</LinearLayout>
3.recyclerview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"/>
</LinearLayout>
4.MainActivity.java
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity{
private static final String TAG = MainActivity.class.getSimpleName();
public float firstItemHeightDate;
public float paddingDate;
public float itemHeightDate;
public int allPixelsDate;
public int finalHeightDate;
private DateAdapter dateAdapter;
private ArrayList<LabelerDate> labelerDates = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
getRecyclerviewDate();
}
public void getRecyclerviewDate() {
final RecyclerView recyclerViewDate = (RecyclerView) findViewById(R.id.recycler_view);
if (recyclerViewDate != null) {
recyclerViewDate.postDelayed(new Runnable() {
#Override
public void run() {
setDateValue();
}
}, 300);
/*recyclerViewDate.postDelayed(new Runnable() {
#Override
public void run() {
recyclerViewDate.smoothScrollToPosition(dateAdapter.getItemCount()-1);
setDateValue();
}
}, 5000);*/
}
ViewTreeObserver vtoDate = recyclerViewDate.getViewTreeObserver();
vtoDate.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
recyclerViewDate.getViewTreeObserver().removeOnPreDrawListener(this);
finalHeightDate = recyclerViewDate.getMeasuredHeight();
itemHeightDate = getResources().getDimension(R.dimen.item_dob_height);
paddingDate = (finalHeightDate - itemHeightDate) / 2;
firstItemHeightDate = paddingDate;
allPixelsDate = 0;
final LinearLayoutManager dateLayoutManager = new LinearLayoutManager(getApplicationContext());
dateLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerViewDate.setLayoutManager(dateLayoutManager);
recyclerViewDate.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
synchronized (this) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
calculatePositionAndScrollDate(recyclerView);
}
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
allPixelsDate += dy;
}
});
if (labelerDates == null) {
labelerDates = new ArrayList<>();
}
genLabelerDate();
dateAdapter = new DateAdapter(labelerDates, (int) firstItemHeightDate);
recyclerViewDate.setAdapter(dateAdapter);
dateAdapter.setSelecteditem(dateAdapter.getItemCount() - 1);
return true;
}
});
}
private void genLabelerDate() {
for (int i = 0; i < 32; i++) {
LabelerDate labelerDate = new LabelerDate();
labelerDate.setNumber(Integer.toString(i));
labelerDates.add(labelerDate);
if (i == 0 || i == 31) {
labelerDate.setType(DateAdapter.VIEW_TYPE_PADDING);
} else {
labelerDate.setType(DateAdapter.VIEW_TYPE_ITEM);
}
}
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void calculatePositionAndScrollDate(RecyclerView recyclerView) {
int expectedPositionDate = Math.round((allPixelsDate + paddingDate - firstItemHeightDate) / itemHeightDate);
if (expectedPositionDate == -1) {
expectedPositionDate = 0;
} else if (expectedPositionDate >= recyclerView.getAdapter().getItemCount() - 2) {
expectedPositionDate--;
}
scrollListToPositionDate(recyclerView, expectedPositionDate);
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void scrollListToPositionDate(RecyclerView recyclerView, int expectedPositionDate) {
float targetScrollPosDate = expectedPositionDate * itemHeightDate + firstItemHeightDate - paddingDate;
float missingPxDate = targetScrollPosDate - allPixelsDate;
if (missingPxDate != 0) {
//recyclerView.smoothScrollBy((int) missingPxDate, 0);//horizontal
recyclerView.smoothScrollBy(0, (int) missingPxDate);//virtical
}
setDateValue();
}
//
private void setDateValue() {
int expectedPositionDateColor = Math.round((allPixelsDate + paddingDate - firstItemHeightDate) / itemHeightDate);
int setColorDate = expectedPositionDateColor + 1;
//set color here
dateAdapter.setSelecteditem(setColorDate);
}
public class DateAdapter extends RecyclerView.Adapter<DateAdapter.DateViewHolder> {
private ArrayList<LabelerDate> dateDataList;
private static final int VIEW_TYPE_PADDING = 1;
private static final int VIEW_TYPE_ITEM = 2;
private int paddingHeightDate = 0;
private int selectedItem = -1;
public DateAdapter(ArrayList<LabelerDate> dateData, int paddingHeightDate) {
this.dateDataList = dateData;
this.paddingHeightDate = paddingHeightDate;
}
#Override
public DateViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item,
parent, false);
return new DateViewHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item,
parent, false);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
layoutParams.height = paddingHeightDate;
view.setLayoutParams(layoutParams);
return new DateViewHolder(view);
}
}
#Override
public void onBindViewHolder(DateViewHolder holder, int position) {
LabelerDate labelerDate = dateDataList.get(position);
if (getItemViewType(position) == VIEW_TYPE_ITEM) {
holder.tvDate.setText(labelerDate.getNumber());
holder.tvDate.setVisibility(View.VISIBLE);
Log.d(TAG, "default " + position + ", selected " + selectedItem);
if (position == selectedItem) {
Log.d(TAG, "center" + position);
holder.tvDate.setTextColor(Color.parseColor("#76FF03"));
holder.tvDate.setTextSize(35);
} else {
holder.tvDate.setTextColor(Color.BLACK);
holder.tvDate.setTextSize(18);
}
} else {
holder.tvDate.setVisibility(View.INVISIBLE);
}
}
public void setSelecteditem(int selecteditem) {
this.selectedItem = selecteditem;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return dateDataList.size();
}
#Override
public int getItemViewType(int position) {
LabelerDate labelerDate = dateDataList.get(position);
if (labelerDate.getType() == VIEW_TYPE_PADDING) {
return VIEW_TYPE_PADDING;
} else {
return VIEW_TYPE_ITEM;
}
}
public class DateViewHolder extends RecyclerView.ViewHolder {
public TextView tvDate;
public DateViewHolder(View itemView) {
super(itemView);
tvDate = (TextView) itemView.findViewById(R.id.tv_year);
}
}
}
private class LabelerDate {
private int type;
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
}

Dynamic Endless RecyclerView scrolling issues

I have to create following layout
So far, I have successfully created the layout and populated all views. However, I am facing problem in the making ReyclerView Endless on first fragment.
Consider the RecyclerView has 10 items on first load, now on scroll I am adding another 10 items and so on. However, the RecyclerView isn't displaying those items, it's height gets fixed at the end of 10th element. I know that the elements are loaded correctly in RecyclerView and if I try to scroll with two fingers on emulator (GenyMotion), the RecyclerView scrolls just fine.
Update :-
Code for RecyclerView's Fragment -
public class CheckInFragmentRecyclerAdapter extends RecyclerView.Adapter<CheckInFragmentRecyclerAdapter.ViewHolder> {
final List<StoreNew> stores;
public CheckInFragmentRecyclerAdapter(final List<StoreNew> stores) {
this.stores = stores;
}
#Override
public CheckInFragmentRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_check_in_fragment, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(CheckInFragmentRecyclerAdapter.ViewHolder holder, int position) {
// Setting data
}
#Override
public int getItemCount() {
return stores.size();
}
/**
* Function to clear existing data from list
* #param stores StoreNew instance containing store information
*/
public void update(final List<StoreNew> stores) {
this.stores.clear();
this.stores.addAll(stores);
notifyDataSetChanged();
}
/**
* Function to add more data to list
* #param stores StoreNew instance containing store information
*/
public void addNewList(final List<StoreNew> stores) {
this.stores.addAll(stores);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
// Initializing component
}
}
}
Update :-
Adding layouts for used screens.
main_screen.xml - This is the home screen
<android.support.v4.widget.NestedScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/home_footer"
android:layout_below="#+id/toolbar"
android:fillViewport="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Sliding Tab for showing images -->
<com.example.slidingtab.SlidingTabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white" />
<!-- ViewPager for Images -->
<android.support.v4.view.ViewPager
android:id="#+id/vpOffers"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginTop="8dp" />
<!-- Segmented Control for fragments -->
<info.hoang8f.android.segmented.SegmentedGroup xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
android:id="#+id/segmented2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
segmentedgroup:sc_border_width="1dp"
segmentedgroup:sc_corner_radius="4dp"
segmentedgroup:sc_tint_color="#color/black">
<RadioButton
android:id="#+id/rbTab1"
style="#style/segmented_radio_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="true"
android:textSize="#dimen/normal_text"
android:text="#string/check_in" />
<RadioButton
android:id="#+id/rbTab2"
style="#style/segmented_radio_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="#dimen/normal_text"
android:text="#string/upload_bill" />
<RadioButton
android:id="#+id/rbTab3"
style="#style/segmented_radio_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="#dimen/normal_text"
android:text="#string/redeem" />
</info.hoang8f.android.segmented.SegmentedGroup>
<!-- Custom wrap content ViewPager containing fragments -->
<!-- This will make sure that the height of ViewPager is equal to height of Fragment -->
<com.example.ui.custom.WrapContentHeightViewPager
android:id="#+id/vpFragments"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-7dp" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
WrapContentHeightViewPager.java
public class WrapContentHeightViewPager extends ViewPager {
private static final String TAG = WrapContentHeightViewPager.class.getSimpleName();
private int height = 0;
private int decorHeight = 0;
private int widthMeasuredSpec;
private boolean animateHeight;
private int rightHeight;
private int leftHeight;
private int scrollingPosition = -1;
private boolean enabled;
public WrapContentHeightViewPager(Context context) {
super(context);
init();
}
public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
init();
}
private void init() {
addOnPageChangeListener(new OnPageChangeListener() {
public int state;
#Override
public void onPageScrolled(int position, float offset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
if (state == SCROLL_STATE_IDLE) {
height = 0; // measure the selected page in-case it's a change without scrolling
Log.d(TAG, "onPageSelected:" + position);
}
}
#Override
public void onPageScrollStateChanged(int state) {
this.state = state;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return this.enabled && super.onTouchEvent(event);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return this.enabled && super.onInterceptTouchEvent(event);
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
#Override
public void setAdapter(PagerAdapter adapter) {
height = 0; // so we measure the new content in onMeasure
super.setAdapter(new PagerAdapterWrapper(adapter));
}
/**
* Allows to redraw the view size to wrap the content of the bigger child.
*
* #param widthMeasureSpec with measured
* #param heightMeasureSpec height measured
*/
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
widthMeasuredSpec = widthMeasureSpec;
int mode = MeasureSpec.getMode(heightMeasureSpec);
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
if(height == 0) {
// measure vertical decor (i.e. PagerTitleStrip) based on ViewPager implementation
decorHeight = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
LayoutParams lp = (LayoutParams) child.getLayoutParams();
if(lp != null && lp.isDecor) {
int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM;
if(consumeVertical) {
decorHeight += child.getMeasuredHeight() ;
}
}
}
// make sure that we have an height (not sure if this is necessary because it seems that onPageScrolled is called right after
int position = getCurrentItem();
View child = getViewAtPosition(position);
if (child != null) {
height = measureViewHeight(child);
}
//Log.d(TAG, "onMeasure height:" + height + " decor:" + decorHeight);
}
int totalHeight = height + decorHeight + getPaddingBottom() + getPaddingTop();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(totalHeight, MeasureSpec.EXACTLY);
//Log.d(TAG, "onMeasure total height:" + totalHeight);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
#Override
public void onPageScrolled(int position, float offset, int positionOffsetPixels) {
super.onPageScrolled(position, offset, positionOffsetPixels);
// cache scrolled view heights
if (scrollingPosition != position) {
scrollingPosition = position;
// scrolled position is always the left scrolled page
View leftView = getViewAtPosition(position);
View rightView = getViewAtPosition(position + 1);
if (leftView != null && rightView != null) {
leftHeight = measureViewHeight(leftView);
rightHeight = measureViewHeight(rightView);
animateHeight = true;
//Log.d(TAG, "onPageScrolled heights left:" + leftHeight + " right:" + rightHeight);
} else {
animateHeight = false;
}
}
if (animateHeight) {
int newHeight = (int) (leftHeight * (1 - offset) + rightHeight * (offset));
if (height != newHeight) {
//Log.d(TAG, "onPageScrolled height change:" + newHeight);
height = newHeight;
requestLayout();
invalidate();
}
}
}
private int measureViewHeight(View view) {
view.measure(getChildMeasureSpec(widthMeasuredSpec, getPaddingLeft() + getPaddingRight(), view.getLayoutParams().width), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
return view.getMeasuredHeight();
}
protected View getViewAtPosition(int position) {
if(getAdapter() != null) {
Object objectAtPosition = ((PagerAdapterWrapper) getAdapter()).getObjectAtPosition(position);
if (objectAtPosition != null) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child != null && getAdapter().isViewFromObject(child, objectAtPosition)) {
return child;
}
}
}
}
return null;
}
/**
* Wrapper for PagerAdapter so we can ask for Object at index
*/
private class PagerAdapterWrapper extends PagerAdapter {
private final PagerAdapter innerAdapter;
private SparseArray<Object> objects;
public PagerAdapterWrapper(PagerAdapter adapter) {
this.innerAdapter = adapter;
this.objects = new SparseArray<>(adapter.getCount());
}
#Override
public void startUpdate(ViewGroup container) {
innerAdapter.startUpdate(container);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = innerAdapter.instantiateItem(container, position);
objects.put(position, object);
return object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
innerAdapter.destroyItem(container, position, object);
objects.remove(position);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
innerAdapter.setPrimaryItem(container, position, object);
}
#Override
public void finishUpdate(ViewGroup container) {
innerAdapter.finishUpdate(container);
}
#Override
public Parcelable saveState() {
return innerAdapter.saveState();
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
innerAdapter.restoreState(state, loader);
}
#Override
public int getItemPosition(Object object) {
return innerAdapter.getItemPosition(object);
}
#Override
public void notifyDataSetChanged() {
innerAdapter.notifyDataSetChanged();
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
innerAdapter.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
innerAdapter.unregisterDataSetObserver(observer);
}
#Override
public float getPageWidth(int position) {
return innerAdapter.getPageWidth(position);
}
#Override
public CharSequence getPageTitle(int position) {
return innerAdapter.getPageTitle(position);
}
#Override
public int getCount() {
return innerAdapter.getCount();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return innerAdapter.isViewFromObject(view, object);
}
public Object getObjectAtPosition(int position) {
return objects.get(position);
}
}
}
first_fragment.xml
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lvCheckIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:requiresFadingEdge="none"
android:fadingEdgeLength="0dp"
android:orientation="vertical" />
Adding more data to the RecyclerView on scrolling -
private RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = recyclerView.getChildCount();
totalItemCount = adapter.getItemCount();
firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold) && current_page < totalPages) {
// End has been reached
// Do something
current_page++;
// Sending request to server
loading = true;
}
}
};
When data is received via API (adapter already added above)-
adapter.addNewList(homePageNew.checkin_stores.stores);
There seems to be a similar discussion here: ViewPager in a NestedScrollView
Maybe the sample of the Naruto guy (https://github.com/TheLittleNaruto/SupportDesignExample/) could solve your situation.
Edit
I'm not sure if I'm getting the point of your question. Anyway here you can a possible solution to your situation.
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/app_bar_layout"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
>
---- include here everything before the pager ----
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
---- this is your pager
<include layout="#layout/fragment_pager"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/app_bar_layout"
/>
</android.support.design.widget.CoordinatorLayout>
Then you can just listen to the RecycleView in the pager to add items as the RecycleView scrolls to bottom.
I hope it helped
You can see my implementation of the endless RecyclerView scroll:
GalleryActivity.java
public class GalleryActivity extends AppCompatActivity {
private StaggeredGridLayoutManager layoutManager;
private RecyclerView recyclerView;
private ImageRecyclerViewAdapter imageAdapter;
private List<ImageItem> images;
private ImageSearchClient imageSearchClient;
private String query;
private int currentStartPosition = 1;
private boolean loading = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
getSupportActionBar().setHomeButtonEnabled(true);
query = getIntent().getStringExtra(Utils.QUERY_TAG);
if (query == null)
return;
imageSearchClient = new ImageSearchClient(query);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new StaggeredGridLayoutManager(2, 1);
recyclerView.setLayoutManager(layoutManager);
images = new ArrayList<>();
imageAdapter = new ImageRecyclerViewAdapter(this, images);
recyclerView.setAdapter(imageAdapter);
recyclerView.addOnScrollListener(new EndlessRecyclerScrollListener());
loadMoreData();
}
private void loadMoreData() {
loading = true;
imageSearchClient.getService().customSearch(Utils.API_KEY, Utils.CX_KEY, query,
Utils.IMAGE_SEARCH_TYPE,
currentStartPosition,
Utils.ITEMS_COUNT,
new Callback<ImageResponse>() {
#Override
public void success(ImageResponse imageResponse, Response response) {
List<ImageItem> items = imageResponse.getItems();
for (ImageItem item : items) {
images.add(item);
}
imageAdapter.notifyDataSetChanged();
currentStartPosition += items.size();
loading = false;
}
#Override
public void failure(RetrofitError error) {
Log.e(GalleryActivity.class.getSimpleName(),
error.getResponse().getReason());
}
});
}
private class EndlessRecyclerScrollListener extends RecyclerView.OnScrollListener {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int[] visibleItems = layoutManager.findLastVisibleItemPositions(null);
int lastItem = 0;
for (int i : visibleItems) {
lastItem = Math.max(lastItem, i);
}
if (lastItem > 0 && lastItem > images.size() - Utils.ITEMS_COUNT && !loading) {
if (NetworkUtils.hasConnection(GalleryActivity.this)) {
loadMoreData();
} else {
Toast.makeText(GalleryActivity.this, R.string.network_error,
Toast.LENGTH_SHORT).show();
}
}
}
}
}
ImageRecyclerViewAdapter.java (nothing is extraordinary here):
public class ImageRecyclerViewAdapter extends RecyclerView.Adapter<ImageViewHolder> {
private List<ImageItem> itemList;
private Context context;
private int parentWidth = 0;
public ImageRecyclerViewAdapter(Context context, List<ImageItem> itemList) {
this.context = context;
this.itemList = itemList;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_card_item, null);
ImageViewHolder imageViewHolder = new ImageViewHolder(layoutView);
parentWidth = parent.getWidth();
return imageViewHolder;
}
#Override
public void onBindViewHolder(final ImageViewHolder holder, int position) {
Picasso.with(context)
.load(itemList.get(position).getLink())
.error(R.drawable.error_image)
.placeholder(R.drawable.progress_animation)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
int targetWidth = parentWidth / 2;
float ratio = (float) bitmap.getHeight() / (float) bitmap.getWidth();
float heightFloat = ((float) targetWidth) * ratio;
final android.view.ViewGroup.MarginLayoutParams layoutParams
= (ViewGroup.MarginLayoutParams) holder.image.getLayoutParams();
layoutParams.height = (int) heightFloat;
layoutParams.width = (int) targetWidth;
holder.image.setLayoutParams(layoutParams);
holder.image.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
#Override
public int getItemCount() {
return this.itemList.size();
}
}

Android - Rotation menu with one part out of the screen

I want develope this rotation in my App . I have implemented the "down" menu ("můj dealer", "moje Volvo", "kontakty") and I need implement the "upper" rotating menu.
How can I do it? Do you have tips? Hope you understand me.
Images (please, watch the video above in the link):
Menu_item_test.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/menuItemImg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/tab_1_1" />
</RelativeLayout>
Activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/rotationMenu" >
</FrameLayout>
<ImageView
android:id="#+id/imageViewShadow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="60dp"
android:contentDescription="shadow"
android:scaleType="fitXY"
android:src="#drawable/half_round_back" />
<cz.mixedapps.volvista.RotationMenu
android:id="#+id/rotationMenu"
android:layout_width="match_parent"
android:layout_height="265dp"
android:layout_alignParentBottom="true" >
</cz.mixedapps.volvista.RotationMenu>
</RelativeLayout>
I have put together a custom view which replicates the behaviour, you still have to style it like in you example, but it works with an arbitrary number of child views and currently looks like this:
EDIT: I added the ability to show and hide the upper rotating menu with two methods, showRotationMenu() and hideRotationMenu():
Of course there is a lot you can do to improve this view. I just wrote this in 15 minutes and therefor it is a little rough around the edges. But it should be more than enough to put you on the right track. Both the looks of the buttons and of the views which rotate is completely customisable.
1) Source
RotationMenu.java:
import android.content.Context;
import android.content.res.Resources;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.*;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
/**
* Created by Xaver Kapeller on 26/03/14.
*/
public class RotationMenu extends LinearLayout {
private final DataSetObserver dataSetObserver = new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
reloadAdapter();
}
};
private RotationMenuAdapter adapter;
private FrameLayout flViewContainer;
private LinearLayout llMenu;
private View currentView;
private View previousView;
private int animationPivotX;
private int animationPivotY;
private int selectedPosition = 0;
public RotationMenu(Context context) {
super(context);
setupMenu();
}
public RotationMenu(Context context, AttributeSet attrs) {
super(context, attrs);
setupMenu();
}
public RotationMenu(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setupMenu();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
this.animationPivotX = w / 2;
this.animationPivotY = h;
}
private void setupMenu() {
this.setOrientation(VERTICAL);
this.flViewContainer = new FrameLayout(getContext());
this.addView(this.flViewContainer, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dpToPixel(150)));
this.llMenu = new LinearLayout(getContext());
this.llMenu.setOrientation(LinearLayout.HORIZONTAL);
this.addView(this.llMenu, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
private int dpToPixel(int dp) {
float scale = getDisplayDensityFactor();
return (int) (dp * scale + 0.5f);
}
private float getDisplayDensityFactor() {
Resources res = getResources();
if (res != null) {
DisplayMetrics metrics = res.getDisplayMetrics();
if(metrics != null) {
return metrics.density;
}
}
return 1.0f;
}
public RotationMenuAdapter getAdapter() {
return this.adapter;
}
public void setAdapter(RotationMenuAdapter adapter) {
if (adapter != null) {
if (this.adapter != null) {
this.adapter.unregisterDataSetObserver(this.dataSetObserver);
}
adapter.registerDataSetObserver(this.dataSetObserver);
this.adapter = adapter;
reloadAdapter();
}
}
public boolean isRotationMenuVisible() {
return this.flViewContainer.getVisibility() == View.VISIBLE;
}
public void showRotationMenu() {
if(this.flViewContainer.getVisibility() != View.VISIBLE) {
this.flViewContainer.setVisibility(View.VISIBLE);
AnimationSet set = new AnimationSet(false);
TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0);
translateAnimation.setDuration(1000);
set.addAnimation(translateAnimation);
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setDuration(1000);
set.addAnimation(alphaAnimation);
this.flViewContainer.startAnimation(set);
}
}
public void hideRotationMenu() {
if(this.flViewContainer.getVisibility() == View.VISIBLE) {
AnimationSet set = new AnimationSet(false);
TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);
translateAnimation.setDuration(1000);
set.addAnimation(translateAnimation);
AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
alphaAnimation.setDuration(1000);
set.addAnimation(alphaAnimation);
set.setAnimationListener(new ViewAnimationEndListener(this.flViewContainer) {
#Override
protected void onAnimationEnd(Animation animation, View view) {
view.setVisibility(View.GONE);
}
});
this.flViewContainer.startAnimation(set);
}
}
private void reloadAdapter() {
Context context = getContext();
if (this.adapter != null && context != null) {
int viewCount = this.adapter.getCount();
int oldViewCount = this.llMenu.getChildCount();
for (int i = 0; i < Math.max(oldViewCount, viewCount); i++) {
if (i < viewCount) {
LayoutParams layoutParams = new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
View menuItem;
if (i < this.llMenu.getChildCount()) {
menuItem = this.adapter.getMenuItemView(i, this.llMenu.getChildAt(i), this.llMenu);
if(menuItem.getParent() == null) {
this.llMenu.removeViewAt(i);
this.llMenu.addView(menuItem, i, layoutParams);
}
} else {
menuItem = this.adapter.getMenuItemView(i, null, this.llMenu);
this.llMenu.addView(menuItem, layoutParams);
}
menuItem.setOnClickListener(new MenuItemClickListener(i));
} else {
this.llMenu.removeViewAt(i);
}
}
this.flViewContainer.removeAllViews();
this.previousView = this.currentView;
if (this.selectedPosition >= viewCount) {
this.selectedPosition = viewCount - 1;
}
this.currentView = this.adapter.getView(this.selectedPosition, this.previousView, this);
addViewWithAnimation(this.currentView, false);
}
}
public void switchToItem(int position, boolean animate) {
if (this.adapter != null) {
int viewCount = this.adapter.getCount();
position = valueInRange(position, 0, viewCount - 1);
if (position != this.selectedPosition) {
View oldView = this.currentView;
this.currentView = this.adapter.getView(position, this.previousView, this);
this.previousView = oldView;
addViewWithAnimation(this.currentView, animate, position < this.selectedPosition);
removeViewWithAnimation(this.previousView, animate, position < this.selectedPosition);
this.selectedPosition = position;
}
}
}
private int valueInRange(int value, int min, int max) {
if (value > max) {
value = max;
} else if (value < min) {
value = min;
}
return value;
}
private void addViewWithAnimation(View view, boolean animate, boolean leftToRight) {
if (view != null) {
if(view.getParent() == null) {
this.flViewContainer.addView(view, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
if (animate) {
int start = leftToRight ? -90 : 90;
Animation rotateIn = new RotateAnimation(start, 0, this.animationPivotX, this.animationPivotY);
rotateIn.setDuration(1000);
view.startAnimation(rotateIn);
}
}
}
private void addViewWithAnimation(View view, boolean animate) {
addViewWithAnimation(view, animate, true);
}
private void removeViewWithAnimation(View view, boolean animate, boolean leftToRight) {
if (view != null) {
if (animate) {
int target = leftToRight ? 90 : -90;
Animation rotateOut = new RotateAnimation(0, target, this.animationPivotX, this.animationPivotY);
rotateOut.setDuration(1000);
rotateOut.setAnimationListener(new ViewAnimationEndListener(view) {
#Override
protected void onAnimationEnd(Animation animation, View view) {
flViewContainer.removeView(view);
}
});
view.startAnimation(rotateOut);
} else {
this.flViewContainer.removeView(view);
}
}
}
private void removeViewWithAnimation(View view, boolean animate) {
removeViewWithAnimation(view, animate, true);
}
private abstract class ViewAnimationEndListener implements Animation.AnimationListener {
private final View view;
private ViewAnimationEndListener(View view) {
this.view = view;
}
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
onAnimationEnd(animation, this.view);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
protected abstract void onAnimationEnd(Animation animation, View view);
}
private class MenuItemClickListener implements OnClickListener {
private final int position;
MenuItemClickListener(int position) {
this.position = position;
}
#Override
public void onClick(View v) {
if(adapter != null && adapter.isMenuItemEnabled(this.position) && isRotationMenuVisible()) {
switchToItem(this.position, true);
}
}
}
}
RotationMenuAdapter.java:
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* Created by Xaver Kapeller on 26/03/14.
*/
public abstract class RotationMenuAdapter extends BaseAdapter {
public abstract View getMenuItemView(int position, View convertView, ViewGroup parent);
public abstract long getMenuItemId(int position);
public abstract boolean isMenuItemEnabled(int position);
}
2) Usage:
The custom view is making use of adapters and view recycling, so you use it the same way you would use a ListView. Because of the view recycling it is not very memory intensive and actually pretty fast. The logic for the creating of the menu items at the bottom is also in the adapter and it too uses view recycling. So be sure that you implement getMenuItemView() with the same care you would use to implement getView(). First you have to write an adapter:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import at.test.app.R;
import at.test.app.RotationMenu.RotationMenuAdapter;
import java.util.List;
/**
* Created by Xaver Kapeller on 26/03/14.
*/
public class TestAdapter extends RotationMenuAdapter {
private static final long TEST_VIEW_ID = 0;
private static final long DEFAULT_VIEW_ID = TEST_VIEW_ID;
private static final long TEST_MENU_ID = 0;
private static final long DEFAULT_MENU_ID = TEST_MENU_ID;
private final LayoutInflater inflater;
private final List<TestViewModel> viewModels;
public TestAdapter(Context context, List<TestViewModel> viewModels) {
this.inflater = LayoutInflater.from(context);
this.viewModels = viewModels;
}
#Override
public int getCount() {
return this.viewModels.size();
}
#Override
public Object getItem(int position) {
return this.viewModels.get(position);
}
#Override
public long getItemId(int position) {
Object viewModel = getItem(position);
if(viewModel instanceof TestViewModel) {
return TEST_VIEW_ID;
}
return DEFAULT_VIEW_ID;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(getItemId(position) == TEST_VIEW_ID) {
TestViewModel viewModel = (TestViewModel) getItem(position);
TestRow row;
if(convertView == null) {
convertView = this.inflater.inflate(TestRow.LAYOUT, parent, false);
row = new TestRow(convertView);
convertView.setTag(row);
}
row = (TestRow) convertView.getTag();
row.bind(viewModel);
}
return convertView;
}
#Override
public View getMenuItemView(int position, View convertView, ViewGroup parent) {
if(getMenuItemId(position) == TEST_MENU_ID) {
TestViewModel viewModel = (TestViewModel)getItem(position);
MenuRow row;
if(convertView == null) {
convertView = this.inflater.inflate(MenuRow.LAYOUT, parent, false);
row = new MenuRow(convertView);
convertView.setTag(row);
}
row = (MenuRow)convertView.getTag();
row.bind(viewModel);
}
return convertView;
}
#Override
public long getMenuItemId(int position) {
Object item = getItem(position);
if(item instanceof TestViewModel) {
return TEST_MENU_ID;
}
return DEFAULT_MENU_ID;
}
#Override
public boolean isMenuItemEnabled(int position) {
return true;
}
}
Nothing special, except the extra methods for the creating of the menu items. In isMenuItemEnabled() you can add logic to enable/disable menu items if you need to.
And then you apply your adapter to the view:
List<TestViewModel> viewModels = new ArrayList<TestViewModel>();
TestViewModel menuItemOne = new TestViewModel();
menuItemOne.setMenuItemIconResId(R.drawable.icon);
viewModels.add(menuItemOne);
TestViewModel menuItemTwo = new TestViewModel();
menuItemTwo.setMenuItemIconResId(R.drawable.icon);
viewModels.add(menuItemTwo);
TestAdapter adapter = new TestAdapter(getActivity(), viewModels);
this.rotationMenu.setAdapter(adapter);
EDIT:
Try this layout with wrap_content instead match_parent:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/menuItemImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#drawable/tab_1_1" />
</RelativeLayout>
I'm also no so sure about your layout_width, are you sure you need match_parent there? I don't think so.

Categories

Resources