Sticky header in android project - android

I have a view in my android project like :
I want to show a header when I scroll down when the Title (lblHeaderJobTitle in the code below) reaches the top, and hide it back when the title is visible in the screen when I scroll up.
<androidx.coordinatorlayout.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">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayoutHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
android:paddingStart="#dimen/margin4"
android:paddingEnd="#dimen/margin4"
android:layout_gravity="top"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<TextView
android:id="#+id/lblHeaderJobTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/poppins_semibold"
android:textSize="#dimen/t4"
android:includeFontPadding="false"
android:textColor="#color/darkGrey"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:MvxBind="Text Title"/>
<TextView
android:id="#+id/lblHeaderJobCompanyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="#dimen/margin2"
android:fontFamily="#font/mulish_bold"
android:textSize="#dimen/t2"
android:textColor="#color/darkGrey"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/lblHeaderJobTitle"
app:layout_constraintEnd_toStartOf="#id/verticalSeparatorHeader"
app:MvxBind="Text CompanyName"/>
<TextView
android:id="#+id/verticalSeparatorHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="|"
android:fontFamily="#font/mulish_regular"
android:textSize="#dimen/t2"
android:textColor="#color/darkGrey"
app:layout_constraintTop_toTopOf="#id/lblHeaderJobCompanyName"
app:layout_constraintStart_toEndOf="#id/lblHeaderJobCompanyName"
app:layout_constraintEnd_toStartOf="#id/lblHeaderJobLocation"/>
<TextView
android:id="#+id/lblHeaderJobLocation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/mulish_regular"
android:textSize="#dimen/t2"
android:textColor="#color/darkGrey"
android:layout_marginLeft="#dimen/margin2"
app:layout_constraintTop_toTopOf="#id/lblHeaderJobCompanyName"
app:layout_constraintStart_toEndOf="#id/verticalSeparatorHeader"
app:MvxBind="Text LblLocation"/>
<View
android:id="#+id/imgHeaderSeparator"
android:layout_width="0dp"
android:layout_height="1dp"
android:background="#color/silver"
android:layout_marginTop="11dp"
app:layout_constraintTop_toBottomOf="#id/lblHeaderJobLocation"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.core.widget.NestedScrollView
android:id="#+id/nestedScrollViewJobDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="#dimen/margin4"
android:paddingEnd="#dimen/margin4">
<ImageView
android:id="#+id/imgBrandingLogo"
android:layout_width="match_parent"
android:layout_height="100dp"
android:scaleType="centerInside"
android:background="#drawable/bg_roundrect_ripple_light_border"
app:MvxBind="DrawableName DefaultCompanyPhotoDrawable"/>
<TextView
android:id="#+id/lblJobTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/margin3"
android:layout_marginBottom="#dimen/margin2"
android:fontFamily="#font/poppins_semibold"
android:textSize="#dimen/t8"
android:includeFontPadding="false"
android:textColor="#color/darkGrey"
app:layout_constraintTop_toBottomOf="#id/relativeLayoutJobDetail"
app:MvxBind="Text Title"/>
<ImageView
android:id="#+id/imgJobLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/margin1"
android:src="#drawable/ic_location_on_black_24dp"
app:layout_constraintTop_toBottomOf="#id/lblJobTitle"/>
<TextView
android:id="#+id/lblJobCompanyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin2"
android:layout_marginRight="#dimen/margin2"
android:fontFamily="#font/mulish_bold"
android:textSize="#dimen/t4"
android:textColor="#color/darkGrey"
app:layout_constraintStart_toEndOf="#id/imgJobLocation"
app:layout_constraintTop_toTopOf="#id/imgJobLocation"
app:layout_constraintEnd_toStartOf="#id/verticalSeparator"
app:MvxBind="Text CompanyName"/>
<TextView
android:id="#+id/verticalSeparator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="|"
android:fontFamily="#font/mulish_regular"
android:textSize="#dimen/t4"
android:textColor="#color/darkGrey"
app:layout_constraintTop_toTopOf="#id/lblJobCompanyName"
app:layout_constraintStart_toEndOf="#id/lblJobCompanyName"
app:layout_constraintEnd_toStartOf="#id/lblJobLocation"/>
<TextView
android:id="#+id/lblJobLocation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/mulish_regular"
android:textSize="#dimen/t4"
android:textColor="#color/darkGrey"
android:layout_marginLeft="#dimen/margin2"
app:layout_constraintTop_toTopOf="#id/lblJobCompanyName"
app:layout_constraintStart_toEndOf="#id/verticalSeparator"
app:MvxBind="Text LblLocation"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayoutBtnGroup"
android:layout_width="match_parent"
android:layout_height="63dp"
android:visibility="invisible"
android:paddingStart="#dimen/margin4"
android:paddingEnd="#dimen/margin4"
android:paddingBottom="#dimen/margin2"
android:layout_gravity="center_horizontal|bottom">
<Button
style="#style/Button.Tertiary"
android:id="#+id/btnSaveNow"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:paddingStart="24dp"
android:paddingEnd="24dp"
android:layout_marginLeft="#dimen/margin2"
android:fontFamily="#font/poppins_semibold"
app:icon="#drawable/ic_star_black_24dp"
app:layout_constraintTop_toTopOf="#id/frameLayoutApplyFix"
app:layout_constraintStart_toEndOf="#id/frameLayoutApplyFix"
app:layout_constraintBottom_toBottomOf="#id/frameLayoutApplyFix"
app:layout_constraintEnd_toEndOf="parent"
app:MvxBind="Text BtnSave; Click SaveCommand"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
In my activity I tried this:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
_constraintLayoutHeader = FindViewById<ConstraintLayout>(Resource.Id.constraintLayoutHeader);
_constraintLayoutBtnGroup = FindViewById<ConstraintLayout>(Resource.Id.constraintLayoutBtnGroup);
((CoordinatorLayout.LayoutParams)_constraintLayoutBtnGroup.LayoutParameters).Behavior = new StickyBottomBehavior(Resource.Id.frameLayoutApply, Resource.Id.nestedScrollViewJobDetail, EPosition.Bottom);
((CoordinatorLayout.LayoutParams)_constraintLayoutHeader.LayoutParameters).Behavior = new StickyBottomBehavior(Resource.Id.lblJobLocation, Resource.Id.nestedScrollViewJobDetail, EPosition.Top);
}
In my custom behavior:
public class StickyBottomBehavior : CoordinatorLayout.Behavior
{
#region Properties
private int _anchorId;
private int _scrollViewId;
private EPosition _position;
#endregion
#region Constructor
public StickyBottomBehavior(int anchorId, int scrollViewId, EPosition ePosition)
{
_anchorId = anchorId;
_scrollViewId = scrollViewId;
_position = ePosition;
}
#endregion
public override bool OnStartNestedScroll(CoordinatorLayout coordinatorLayout, Java.Lang.Object child, View directTargetChild, View target, int axes, int type)
{
return (axes == ((int)Vertical));
}
public override void OnNestedPreScroll(CoordinatorLayout coordinatorLayout, Java.Lang.Object child, View target, int dx, int dy, int[] consumed, int type)
{
var anchor = coordinatorLayout.FindViewById(_anchorId);
NestedScrollView scrollView = coordinatorLayout.FindViewById<NestedScrollView>(_scrollViewId);
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams)scrollView.LayoutParameters;
int[] anchorLocation = new int[2];
View childView = child.JavaCast<View>();
anchor.GetLocationInWindow(anchorLocation);
switch (_position)
{
case EPosition.Top:
if (anchorLocation[1] < 0)
{
childView.Visibility = ViewStates.Visible;
layoutParams.TopMargin = childView.Height;
scrollView.LayoutParameters = layoutParams;
}
else
{
childView.Visibility = ViewStates.Invisible;
layoutParams.TopMargin = 0;
scrollView.LayoutParameters = layoutParams;
}
break;
case EPosition.Bottom:
if (anchorLocation[1] < 0)
{
childView.Visibility = ViewStates.Visible;
layoutParams.BottomMargin = childView.Height + 8;
scrollView.LayoutParameters = layoutParams;
}
else
{
childView.Visibility = ViewStates.Invisible;
layoutParams.BottomMargin = 0;
scrollView.LayoutParameters = layoutParams;
}
break;
default:
break;
}
}
}
public enum EPosition
{
Top,
Bottom
}
For the sticky buttons in the bottom it works very well but for the header there is smt wrong when I reach the Title in the top the screen is moving weirdly.
Demo: https://www.veed.io/view/6e1c9b71-b10d-46c7-a284-18b974a0bb7e
Is there another way to do that ? or there is smt wrong in my code ?
Thanks for the help.

Related

Fragment is too slow when change on bottomnavigatioview?

My Fragment is taking so much time in update layout It is because of a lot of code in fragment how to resolve this please help me
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/lyttabs"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:gravity="center"
android:layout_marginTop="20dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.bugfree.caviar.fonts.BabesNeueProBold
android:textStyle="bold"
android:layout_weight="1"
android:textColor="#color/black_text"
android:textSize="30dp"
android:layout_width="0dp"
android:text="My Events That I am..."
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/btn_plus"
android:src="#drawable/plus"
android:layout_width="20dp"
android:layout_height="20dp" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.tabs.TabLayout
app:tabIndicatorColor="#color/button_red_back"
android:id="#+id/tabs"
android:layout_marginTop="15dp"
app:tabBackground="#drawable/tab_indicator_color"
app:tabTextAppearance="#style/MyCustomTextAppearance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
<androidx.viewpager.widget.ViewPager
android:layout_marginTop="30dp"
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
</LinearLayout>
<LinearLayout android:id="#+id/lytCreateEvent"
android:visibility="gone"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.CreateEvent">
<ImageView
android:layout_marginEnd="15dp"
android:layout_marginStart="15dp"
android:layout_marginTop="30dp"
android:id="#+id/imgBack"
android:src="#drawable/back_black"
android:layout_width="20dp"
android:layout_height="20dp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_marginEnd="15dp"
android:layout_marginStart="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<com.bugfree.caviar.fonts.BabesNeueProBold
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create event"
android:textColor="#color/black"
android:textSize="30dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:orientation="vertical">
<com.bugfree.caviar.fonts.BabesNeueProBoldRegular
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Event title" />
<EditText
android:singleLine="true"
android:paddingStart="15dp"
android:layout_marginTop="10dp"
android:textColorHint="#color/black"
android:background="#drawable/edit_back"
android:id="#+id/edtEventTitle"
android:textSize="18dp"
android:layout_gravity="center"
android:hint="Beach Yoga!"
android:layout_width="match_parent"
android:layout_height="50dp" />
</LinearLayout>
<LinearLayout
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.bugfree.caviar.fonts.BabesNeueProBoldRegular
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Event type" />
</LinearLayout>
<RelativeLayout
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:gravity="center"
android:background="#drawable/edit_back"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<com.bugfree.caviar.fonts.BabesNeueProBoldRegular
android:layout_centerVertical="true"
android:paddingStart="15dp"
android:layout_width="wrap_content"
android:textColor="#color/black"
android:layout_height="wrap_content"
android:text="Business"
android:textSize="18dp" />
<ImageView
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_marginEnd="15dp"
android:layout_width="12dp"
android:layout_height="12dp"
android:layout_alignParentEnd="true"
android:src="#drawable/down_arrow" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<com.bugfree.caviar.fonts.BabesNeueProBoldRegular
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event description" />
<com.bugfree.caviar.fonts.BabesNeueProBoldRegular
android:layout_marginEnd="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:text="94/300" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/custombutton_border_edittext"
android:orientation="vertical">
<EditText
android:textSize="18dp"
android:id="#+id/edtDescription"
android:textColorHint="#color/black_text_new"
android:padding="10dp"
android:layout_gravity="start"
android:gravity="start"
android:hint="Beach yoga with Alissia is a lifestyle focused on health,
wellness, and self-care through the practice of"
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#android:color/transparent" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<ImageView
android:layout_marginEnd="10dp"
android:layout_centerVertical="true"
android:tint="#color/black"
android:layout_alignParentEnd="true"
android:src="#drawable/down_arrowsmall"
android:layout_width="10dp"
android:layout_height="10dp" />
</RelativeLayout>
<EditText
android:paddingLeft="10dp"
android:layout_gravity="start"
android:gravity="start"
android:id="#+id/edtSplReq"
android:layout_width="match_parent"
android:layout_marginTop="15dp"
android:layout_height="100dp"
android:singleLine="true"
android:padding="10dp"
android:background="#drawable/lay_without_border"
android:hint="Add a special request[optional]"
android:textColorHint="#848484"
android:textSize="18dp" />
<Button
android:outlineProvider="bounds"
android:stateListAnimator="#null"
style="?android:attr/borderlessButtonStyle"
android:layout_marginBottom="35dp"
android:id="#+id/btnSubmit"
android:layout_marginTop="30dp"
android:textSize="18dp"
android:textAllCaps="false"
android:text="Submit"
android:textColor="#color/space_white"
android:background="#drawable/custombutton"
android:layout_width="match_parent"
android:layout_height="35dp" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:id="#+id/lytTab"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.tabs.TabLayout
app:tabBackground="#drawable/tab_indicator_color"
app:tabIndicatorColor="#color/button_red_back"
android:id="#+id/tabsLOc"
android:layout_marginTop="10dp"
app:tabTextAppearance="#style/MyCustomTextAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPagerLoc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
and here is my fragment
public class EventFragment extends Fragment {
private View view;
ViewPagerAdapter viewPagerAdapter;
LocationPagerAdapter locationPagerAdapter;
private String current = "";
private String ddmmyyyy = "MMDDYYYY";
private Calendar cal = Calendar.getInstance();
FragmentEventBinding binding;
private OnFragmentInteractionListener mListener;
public EventFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(
inflater, R.layout.fragment_event, container, false);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Bebas Neue Pro Regular.otf");
binding.lytTopImg.setOnClickListener(v -> {
binding.lytLocDetails.setVisibility(View.VISIBLE);
binding.lytPartLocNew.setVisibility(View.GONE);
});
binding.imgTopEvent.setImageBitmap(SetBrightness(BitmapFactory.decodeResource(getResources(), R.drawable.dummy),-70));
binding.imgBackLocDetail.setOnClickListener(v -> {
binding.lytLocDetails.setVisibility(View.GONE);
binding.lytPartLocNew.setVisibility(View.VISIBLE);
/* Intent intent = new Intent(PartnerLocationActivity.this, LoactionDetails.class);
startActivity(intent);*/
});
binding.btnPlus.setOnClickListener(v -> {
binding.lyttabs.setVisibility(View.GONE);
binding.lytCreateEvent.setVisibility(View.VISIBLE);
});
binding.imgBack.setOnClickListener(v -> {
mListener.changeFragment(2);
binding.lyttabs.setVisibility(View.VISIBLE);
binding.lytCreateEvent.setVisibility(View.GONE);
});
binding.buttonCreateEvent.setOnClickListener(v -> {
binding.lyttabs.setVisibility(View.VISIBLE);
binding.lytCreateEvent.setVisibility(View.GONE);
});
binding.imgBackPartnerLoc.setOnClickListener(v -> {
binding.lytPartLocNew.setVisibility(View.GONE);
binding.lytCreateEvent.setVisibility(View.VISIBLE);
/* Intent intent = new Intent(getActivity(), CreateEvent.class);
startActivity(intent);*/
});
binding.lytTopPartLoc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
binding.lytLocDetails.setVisibility(View.VISIBLE);
binding.lytPartLocNew.setVisibility(View.GONE);
}
});
binding.buttonCreateEvent.setTypeface(font);
binding.edtEventTitle.setTypeface(font);
binding.edtDescription.setTypeface(font);
binding.edtNameLoc.setTypeface(font);
binding.edtAddressLoc.setTypeface(font);
binding.rdbOne.setTypeface(font);
binding.rdbGroup.setTypeface(font);
binding.buttonPartnerloc.setOnClickListener(v -> {
binding.lytPartLocNew.setVisibility(View.VISIBLE);
binding.lytCreateEvent.setVisibility(View.GONE);
/* Intent intent = new Intent(CreateEvent.this, PartnerLocationActivity.class);
startActivity(intent);*/
});
binding.buttonCreateEvent.setOnClickListener(v -> {
binding.lyttabs.setVisibility(View.VISIBLE);
binding.lytCreateEvent.setVisibility(View.GONE);
});
binding.edtDob.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
String clean = s.toString().replaceAll("[^\\d.]|\\.", "");
String cleanC = current.replaceAll("[^\\d.]|\\.", "");
int cl = clean.length();
int sel = cl;
for (int i = 2; i <= cl && i < 6; i += 2) {
sel++;
}
if (clean.equals(cleanC)) sel--;
if (clean.length() < 8) {
clean = clean + ddmmyyyy.substring(clean.length());
} else {
int day = Integer.parseInt(clean.substring(0, 2));
int mon = Integer.parseInt(clean.substring(2, 4));
int year = Integer.parseInt(clean.substring(4, 8));
mon = mon < 1 ? 1 : mon > 12 ? 12 : mon;
cal.set(Calendar.MONTH, mon - 1);
year = (year < 1900) ? 1900 : (year > 2100) ? 2100 : year;
cal.set(Calendar.YEAR, year);
day = (day > cal.getActualMaximum(Calendar.DATE)) ? cal.getActualMaximum(Calendar.DATE) : day;
clean = String.format("%02d%02d%02d", day, mon, year);
}
clean = String.format("%s/%s/%s", clean.substring(0, 2),
clean.substring(2, 4),
clean.substring(4, 8));
sel = sel < 0 ? 0 : sel;
current = clean;
binding.edtDob.setText(current);
binding.edtDob.setSelection(sel < current.length() ? sel : current.length());
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
new Thread(new Runnable() {
#Override
public void run() {
try {
}catch (Exception ignored){
}
}
}).start();
viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
binding.viewPager.setAdapter(viewPagerAdapter);
binding.tabs.setupWithViewPager( binding.viewPager);
/*binding.imgBack.setOnClickListener(v -> {
binding.lytLocDetails.setVisibility(View.GONE);
binding.lytPartLocNew.setVisibility(View.VISIBLE);
});*/
locationPagerAdapter = new LocationPagerAdapter(getFragmentManager());
binding.viewPagerLoc.setAdapter(locationPagerAdapter);
binding.tabsLOc.setupWithViewPager(binding.viewPagerLoc);
binding.edtSplReq.setTypeface(font);
binding.edtEmail.setTypeface(font);
binding.edtPhone.setTypeface(font);
binding.edtLastName.setTypeface(font);
binding.edtFirstname.setTypeface(font);
binding.btnSubmit.setTypeface(font);
binding.btnFindTable.setTypeface(font);
binding.btnFindTable.setOnClickListener(v -> {
binding.lytBtnFind.setVisibility(View.GONE);
binding.lytTab.setVisibility(View.GONE);
binding.lytBookTable.setVisibility(View.VISIBLE);
});
binding.btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
binding.lyttabs.setVisibility(View.VISIBLE);
binding.lytLocDetails.setVisibility(View.GONE);
binding.lytPartLocNew.setVisibility(View.GONE);
binding.lytCreateEvent.setVisibility(View.GONE);
binding.lytBookTable.setVisibility(View.GONE);
binding.lytBtnFind.setVisibility(View.VISIBLE);
binding.lytTab.setVisibility(View.VISIBLE);
binding.viewPager.setCurrentItem(1);
binding.tabs.getSelectedTabPosition();
}
});
return view = binding.getRoot();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public Bitmap SetBrightness(Bitmap src, int value) {
// original image size
int width = src.getWidth();
int height = src.getHeight();
// create output bitmap
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
// color information
int A, R, G, B;
int pixel;
// scan through all pixels
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
// increase/decrease each channel
R += value;
if(R > 255) { R = 255; }
else if(R < 0) { R = 0; }
G += value;
if(G > 255) { G = 255; }
else if(G < 0) { G = 0; }
B += value;
if(B > 255) { B = 255; }
else if(B < 0) { B = 0; }
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
// return final image
return bmOut;
}
}
There are two parts to this answer.
As per https://developer.android.com/topic/performance/rendering/optimizing-view-hierarchies
Android Layouts allow you to nest UI objects in the view hierarchy. This nesting can also impose a layout cost.
Your layout has multiple levels of nesting, this can have a large cost to layout.
Simplifying you layout with a more flexible layout like a ConstraintLayout Might reduce the layout cost.
Sometimes you are just trying to do too much when creating a view, do some of the work in a background thread and update the view when done (optionally putting up a busy type of progress bar while doing it)
Some idea's based on your code shown.
Instead of scanning every pixel of an image with the SetBrightness method which could take some time depending on the size of the image.
Add the image to the layout without the Brightness adjusted, start background task adjust image Brightness and when done replace the original un-adjusted image with the adjusted image.
This could probably be done without a busy progress bar.
Delay the creation of the offscreen viewpager pages until they are really needed.
Instead of each Fragment in the viewpager creating it's view in onCreateView when the Viewpager is created, create a placeholder view in the Fragment's onCreateView and update it in the Fragment's onResume which is only called when the Fragment is shown on screen (note need a recent'ish version of Viewpager for this behaviour)

How to scroll to chip when clicked in horizontal scroll view?

I have a HorizontalScrollView with a ChipGroup and some Chips. When I check a Chip which is cut out of the screen I want the ScrollView to snap to and show it fully.
This is how it looks like when I select it.
My layout file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
android:background="#color/colorWhite"
android:theme="#style/Theme.MaterialComponents">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="165dp" />
<LinearLayout
android:id="#+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginTop="120dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<HorizontalScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.chip.ChipGroup
android:id="#+id/chip_group"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:chipSpacingHorizontal="10dp"
app:singleLine="true"
app:singleSelection="true"
app:selectionRequired="true">
<com.google.android.material.chip.Chip
android:id="#+id/chip_all"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_marginLeft="15dp"
android:backgroundTint="#color/indicator_chips"
android:checkable="true"
app:chipCornerRadius="10dp"
android:text="ALL"
android:textColor="#color/indicator_text"
app:checkedIconEnabled="false"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
<com.google.android.material.chip.Chip
android:id="#+id/chip_watching"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:checkable="true"
android:text="WATCHING"
android:textColor="#color/indicator_text"
app:chipCornerRadius="10dp"
app:checkedIconEnabled="false"
android:backgroundTint="#color/indicator_chips"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
<com.google.android.material.chip.Chip
android:id="#+id/chip_completed"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:checkable="true"
android:text="COMPLETED"
android:textColor="#color/indicator_text"
app:chipCornerRadius="10dp"
app:checkedIconEnabled="false"
android:backgroundTint="#color/indicator_chips"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
<com.google.android.material.chip.Chip
android:id="#+id/chip_onhold"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:checkable="true"
android:text="ON HOLD"
android:textColor="#color/indicator_text"
app:chipCornerRadius="10dp"
app:checkedIconEnabled="false"
android:backgroundTint="#color/indicator_chips"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
<com.google.android.material.chip.Chip
android:id="#+id/chip_dropped"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:checkable="true"
android:text="DROPPED"
android:textColor="#color/indicator_text"
app:chipCornerRadius="10dp"
app:checkedIconEnabled="false"
android:backgroundTint="#color/indicator_chips"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
<com.google.android.material.chip.Chip
android:id="#+id/chip_plantowatch"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_marginRight="15dp"
android:checkable="true"
android:text="PLAN TO WATCH"
android:textColor="#color/indicator_text"
app:chipCornerRadius="10dp"
app:checkedIconEnabled="false"
android:backgroundTint="#color/indicator_chips"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
</com.google.android.material.chip.ChipGroup>
</HorizontalScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
And my class file:
public class LibraryFragment extends Fragment {
private HorizontalScrollView scrollView;
Chip chip_dropped;
ChipGroup chipGroup;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_library_anime, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
scrollView = view.findViewById(R.id.scroll_view);
chipGroup = view.findViewById(R.id.chip_group);
chipGroup.setOnCheckedChangeListener(checkedListener);
}
ChipGroup.OnCheckedChangeListener checkedListener = new ChipGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(ChipGroup group, int checkedId) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
switch (group.getCheckedChipId()) {
case R.id.chip_all:
fragmentTransaction.replace(R.id.fragment_container, new ListALL()).commit();
break;
case R.id.chip_watching:
fragmentTransaction.replace(R.id.fragment_container, new ListWATCHING()).commit();
break;
case R.id.chip_completed:
fragmentTransaction.replace(R.id.fragment_container, new ListCOMPLETED()).commit();
break;
case R.id.chip_onhold:
fragmentTransaction.replace(R.id.fragment_container, new ListONHOLD()).commit();
break;
case R.id.chip_dropped:
fragmentTransaction.replace(R.id.fragment_container, new ListDROPPED()).commit();
break;
case R.id.chip_plantowatch:
fragmentTransaction.replace(R.id.fragment_container, new ListPLANTOWATCH()).commit();
break;
}
}
};
}
So to repeat, I'm trying to make my ScrollView scroll to a Chip when it is clicked, like the play store with its. I tried .scroolTo and .smoothScrollTo but non of it work.
I made a sample project for You. I think You can easily convert it to Your app.
MainActivity.java
public class MainActivity extends AppCompatActivity
{
HorizontalScrollView scroll;
int widthScreen;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
widthScreen = displayMetrics.widthPixels;
scroll = findViewById(R.id.scroll);
LinearLayout linearLayout = findViewById(R.id.linLay);
for (int index = 0; index <= linearLayout.getChildCount() - 1; index++)
{
linearLayout.getChildAt(index).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Rect r = new Rect();
v.getGlobalVisibleRect(r);
if (r.right == widthScreen)
{
Rect rr = new Rect();
v.getDrawingRect(rr);
scroll.smoothScrollBy(rr.right - (widthScreen - r.left), 0);
}
else if (r.left == 0)
{
Rect rr = new Rect();
v.getDrawingRect(rr);
scroll.smoothScrollBy(rr.right - (widthScreen - r.right), 0);
}
}
});
}
}
}
MainActivity.XML (just buttons in ScrollView)
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linLay"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9" />
</LinearLayout>
</HorizontalScrollView>
When You click on the button which is not fully on-screen ScrollView will be scrolled to a proper position to show full button.
Using the code that #iknow posted, I change it to work exactly like the play store with its Chips
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
chipGroup = view.findViewById(R.id.chip_group);
final Chip chip_all = view.findViewById(R.id.chip_all);
final Chip chip_watching = view.findViewById(R.id.chip_watching);
final Chip chip_completed = view.findViewById(R.id.chip_completed);
final Chip chip_onhold = view.findViewById(R.id.chip_onhold);
final Chip chip_dropped = view.findViewById(R.id.chip_dropped);
final Chip chip_plantowatch = view.findViewById(R.id.chip_plantowatch);
DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
widthScreen = displayMetrics.widthPixels;
scrollView = view.findViewById(R.id.scroll_view);
chipGroup = view.findViewById(R.id.chip_group_anime);
for (int index = 0; index <= chipGroup.getChildCount() - 1; index++) {
chipGroup.getChildAt(index).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Rect r = new Rect();
view.getGlobalVisibleRect(r);
if(chip_all.isChecked()) {
Rect rr = new Rect();
view.getDrawingRect(rr);
scrollView.smoothScrollBy(rr.right - (widthScreen - r.right), 0);
}
if(chip_watching.isChecked()) {
Rect rr = new Rect();
view.getDrawingRect(rr);
scrollView.smoothScrollBy(rr.right - (widthScreen - r.right), 0);
}
if(chip_completed.isChecked()) {
scrollView.smoothScrollTo(chip_completed.getLeft() - (widthScreen / 2) + (chip_completed.getWidth() / 2), 0);
}
if(chip_onhold.isChecked()) {
scrollView.smoothScrollTo(chip_onhold.getLeft() - (widthScreen / 2) + (chip_onhold.getWidth() / 2), 0);
}
if(chip_dropped.isChecked()) {
Rect rr = new Rect();
view.getDrawingRect(rr);
scrollView.smoothScrollBy(r.right, 0);
}
if(chip_plantowatch.isChecked()) {
Rect rr = new Rect();
view.getDrawingRect(rr);
scrollView.smoothScrollBy(r.right, 0);
}
}
});
}
}
The end product looks like the gif above and again thank you to #iknow who provided the code!

Google logo is hide when add parallax effect between bottom sheet and mapView

I'm trying to add a parallel effect in between bottom sheet layout and map view.but google log in map view is hidden when expending the bottom sheet layout. [Google logo is hidden]
show google logo when bottom sheet collapse
I'm using below code:
layout
<android.support.design.widget.CoordinatorLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/Green"
tools:context=".ui.activities.ChooseLocationActivity">
<RelativeLayout
android:id="#+id/map_rlyt"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="com.koya.android.ui.widget.CollapseBehavior"
app:layout_anchor="#+id/bottom_sheet_layout">
<fragment
android:id="#+id/g_map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/category_activity_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/category_search_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/custom_edit_text_margin_top"
android:layout_marginLeft="#dimen/custom_edit_text_margin_left_right"
android:layout_marginRight="#dimen/custom_edit_text_margin_left_right"
android:background="#android:color/transparent">
<android.support.v7.widget.AppCompatImageView
android:id="#+id/ic_back_iv"
android:padding="#dimen/location_activity_back_button_padding"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="#mipmap/ic_back_black"/>
<EditText
android:id="#+id/editTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/custom_edit_text_padding"
android:textColor="#color/black"
android:drawablePadding="8dp"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="1"
android:drawableLeft="#mipmap/ic_search_gray"
android:textCursorDrawable="#drawable/edit_text_cursor_drawable"
android:drawableRight="#mipmap/ic_close_gray"
android:textSize="#dimen/custom_edit_text_text_size"
android:background="#drawable/drawable_custom_edittext"
/>
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"/>
<Button
android:id="#+id/redo_search_in_map_area_button"
style="#style/CategoryChooseButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/category_search_box"
android:layout_centerInParent="true"
android:layout_marginTop="#dimen/fifteen_text_size"
android:animateLayoutChanges="true"
android:paddingEnd="#dimen/redo_search_button_padding"
android:paddingStart="#dimen/redo_search_button_padding"
android:text="#string/redo_search_in_map_area"
android:textAllCaps="false"
android:visibility="gone"
/>
</RelativeLayout>
<include
android:id="#+id/bottom_sheet_layout"
layout="#layout/bottom_sheet"/>
<Button
android:id="#+id/select_location_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="#string/use_selected_location"
android:visibility="gone"
tools:visibility="visible"
style="#style/CategoryChooseButtonStyle"/>
<include android:id="#+id/error_layout"
layout="#layout/error_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
/>
And Implement Coordinatorlayout.Behavior
public class CollapseBehavior<V extends ViewGroup> extends CoordinatorLayout.Behavior<V>{
public CollapseBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onDependentViewChanged(CoordinatorLayout parent, V child, View dependency) {
if (isBottomSheet(dependency)) {
BottomSheetBehavior behavior = ((BottomSheetBehavior) ((CoordinatorLayout.LayoutParams) dependency.getLayoutParams()).getBehavior());
int peekHeight = behavior.getPeekHeight();
// The default peek height is -1, which
// gets resolved to a 16:9 ratio with the parent
final int actualPeek = peekHeight >= 0 ? peekHeight : (int) (((parent.getHeight() * 1.0) / (16.0)) * 9.0);
if (dependency.getTop() >= actualPeek) {
// Only perform translations when the
// view is between "hidden" and "collapsed" states
final int dy = dependency.getTop() - parent.getHeight();
ViewCompat.setTranslationY(child, dy/2);
return true;
}
}
return false;
}
private static boolean isBottomSheet(#NonNull
View view) {
final ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp instanceof CoordinatorLayout.LayoutParams) {
return ((CoordinatorLayout.LayoutParams) lp)
.getBehavior() instanceof BottomSheetBehavior;
}
return false;
}
}
I need this type of scrolling in my application -->
https://streamable.com/g0tf9
How to scroll google map when bottom sheet expend with parallax effect? I would appreciate it a lot!
Thanks in Advance.

How to create ListView item that match material guideline

How to create ListView like this,
google has documentation about this,
https://material.io/guidelines/layout/metrics-keylines.html#metrics-keylines-keylines-spacing
But there is no explaination how to make this,
Here is my attempt so far, I'm not sure about the margin/padding and the separator, is there any tutorial how to make this layout
This is the RecyclerView item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parent_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:transitionName="parent_view"
tools:ignore="UnusedAttribute">
<ImageView
android:id="#+id/image_layanan"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="16dp"
android:transitionName="image_layanan"/>
<TextView
android:id="#+id/text_layanan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="10dp"
android:layout_toEndOf="#id/image_layanan"
android:layout_toRightOf="#+id/image_layanan"
android:textAppearance="?attr/textAppearanceListItem"
android:textSize="16sp"
android:transitionName="text_layanan"
tools:text="string/item_title"/>
<TextView
android:id="#+id/text_dokter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/text_layanan"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/image_layanan"
android:layout_toRightOf="#+id/image_layanan"
android:ellipsize="end"
android:maxLines="1"
android:textAppearance="?attr/textAppearanceListItem"
android:textColor="#212121"
android:textSize="14sp"
android:transitionName="text_dokter"
tools:text="string/item_desc"/>
<TextView
android:id="#+id/text_jam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_dokter"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_toEndOf="#id/image_layanan"
android:layout_toRightOf="#id/image_layanan"
android:textSize="13sp"
android:transitionName="text_jam"/>
<TextView
android:id="#+id/text_pasien"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_jam"
android:layout_marginBottom="14dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_toEndOf="#id/image_layanan"
android:layout_toRightOf="#id/image_layanan"
android:textSize="13sp"
android:transitionName="text_pasien"/>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:layout_alignLeft="#+id/text_pasien"
android:layout_alignStart="#+id/text_pasien"
android:layout_below="#+id/text_pasien"
android:background="#212121"/>
</RelativeLayout>
To get partial divider (or whatever the name) I use this:
create a class extend RecyclerView.ItemDecoration
public class RecyclerViewItemDivider extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
private Drawable mDivider;
public RecyclerViewItemDivider(Context context) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
}
#Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
// this is the left start point for divider,
// I think there is better method without hardcoded the view
// main_content is my RectclerView item main content
// R.dimen.activity_horizontal_margin should be 16dp if use google guidelines
int left = (int)parent.findViewById(R.id.main_content).getX() +
(int)parent.getContext().getResources().getDimension(R.dimen.activity_horizontal_margin);
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
Then you just need to use it like this:
RecyclerViewItemDivider divider = new RecyclerViewItemDivider(recyclerView.getContext());
recyclerView.addItemDecoration(divider);

RecyclerView with pagination in NestedScrollView

Helo, I create a recyclerview with complex items (its CardView with nested RecyclerView with grid layout manager). And I have problem with lags durring scroll. To fix that, I try to put main recyclerView in NestedScrollView, and add scroll listener(when NestedScrollView scrolled to end of content) for pagination. When I scroll first page, it works perfect, but, when new page was loaded, NestedScrollView change own height with freeze. And its look likes some catastrophe. Maybe you faced with some problem?
My recyclerView Item:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/news_item_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="#color/white"
android:layout_margin="5dp"
app:cardElevation="3dp"
app:cardCornerRadius="3dp"
app:cardUseCompatPadding="true"
app:cardPreventCornerOverlap="false">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/news_item_avatar_img"
android:layout_margin="15dp"
android:layout_width="40dp"
android:layout_height="40dp"/>
<TextView
android:layout_marginTop="20dp"
android:layout_marginRight="10dp"
android:layout_toRightOf="#+id/news_item_avatar_img"
android:layout_toLeftOf="#+id/news_item_more_img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/news_item_full_name"
android:textStyle="bold"
android:textSize="12sp"
android:text="Кот черный"
android:textColor="#color/colorAccent"/>
<TextView
android:layout_marginRight="10dp"
android:layout_below="#+id/news_item_full_name"
android:layout_toRightOf="#+id/news_item_avatar_img"
android:layout_toLeftOf="#+id/news_item_more_img"
android:id="#+id/news_item_date"
android:layout_marginTop="5dp"
android:textSize="12sp"
android:textColor="#color/gray_middle"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:visibility="gone"
android:id="#+id/news_item_more_img"
android:layout_alignParentRight="true"
android:layout_marginTop="15dp"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_more_vert_gray_18dp"/>
</RelativeLayout>
<TextView
android:maxLines="6"
android:id="#+id/news_item_content_txt"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/light_black"/>
<android.support.v7.widget.RecyclerView
android:visibility="visible"
android:layout_marginBottom="5dp"
android:id="#+id/news_item_image_container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<RelativeLayout
android:layout_marginRight="15dp"
android:layout_marginLeft="15dp"
android:layout_marginBottom="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_centerVertical="true"
android:id="#+id/news_item_like_count_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_favorite_black_14dp"/>
<TextView
android:layout_toRightOf="#+id/news_item_like_count_img"
android:padding="5dp"
android:layout_centerVertical="true"
android:text="0"
android:textSize="14sp"
android:textColor="#color/gray_middle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/news_item_like_count_txt"/>
<ImageView
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/news_item_like_count_txt"
android:layout_centerVertical="true"
android:id="#+id/news_item_comment_count_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_chat_bubble_black_14dp"/>
<TextView
android:layout_centerVertical="true"
android:padding="5dp"
android:layout_toRightOf="#+id/news_item_comment_count_img"
android:text="0"
android:drawablePadding="5dp"
android:textSize="14sp"
android:textColor="#color/gray_middle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/news_item_comment_count_txt"/>
<ImageView
android:visibility="gone"
android:layout_toLeftOf="#+id/news_item_label_txt"
android:layout_centerVertical="true"
android:id="#+id/news_item_label_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_label_black_14dp"/>
<TextView
android:visibility="gone"
android:gravity="right"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:id="#+id/news_item_label_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#color/gray_middle"
android:text="#string/group_str"/>
</RelativeLayout>
</LinearLayout>
#Override
public void onBindViewHolder(NewsItemHolder holder, final int position) {
final PostEntity postEntity = newsList.get(position);
holder.fullName.setText(userFullName);
holder.date.setText(postEntity.getCreateAt());
holder.content.setText(text);
holder.likeCount.setText(String.valueOf(postEntity.getLikesList().size()));
holder.commentsCount.setText(String.valueOf(postEntity.getCommentsList().size()));
if(postEntity.getUserAvatar() != null) {
Picasso.with(context)
.load(postEntity.getUserAvatar().getThumb())
.fit()
.centerCrop()
.into(holder.avatar);
}
if(postEntity.getPhotosList() != null && postEntity.getPhotosList().size() > 0) {
holder.imageContainer.setVisibility(View.VISIBLE);
int cardWidth = width - dpToPx(16);
ArrayList<PhotoEntity> shortListOfPhoto = new ArrayList<>();
if(postEntity.getPhotosList().size() > 5){
shortListOfPhoto.addAll(postEntity.getPhotosList().subList(0, 5));
} else {
shortListOfPhoto.addAll(postEntity.getPhotosList());
}
final GalleryAdapter galleryAdapter = new GalleryAdapter(context,shortListOfPhoto, postEntity.getPhotosList(), cardWidth);
GridLayoutManager mLayoutManager = new GridLayoutManager(context, 4);
holder.imageContainer.setLayoutManager(mLayoutManager);
mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return ClubUtils.getSpanLookup(galleryAdapter.getItemCount(), position);
}
});
galleryAdapter.setHasStableIds(true);
holder.imageContainer.setNestedScrollingEnabled(false);
holder.imageContainer.setAdapter(galleryAdapter);
holder.imageContainer.setHasFixedSize(true);
} else {
holder.imageContainer.setVisibility(View.GONE);
}
}
Here scroll is NestedScrollView
scroll.getViewTreeObserver().addOnScrollChangedListener(() -> {
View view = (View) scroll.getChildAt(scroll.getChildCount() - 1);
Log.d("CategoryNeswList", scroll.getChildCount() + " child");
int diff = (view.getBottom() - (scroll.getHeight() + scroll
.getScrollY()));
if (diff == 0) {
// getPlaylistFromServer("more");
Toast.makeText(mContext, "Load More", Toast.LENGTH_SHORT).show();
}
});
try to do pagination like this.
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
if (totalItemCount != TOTAL_JOBS) {
loading = false;
Log.e("total", "ite" + totalItemCount + " count" + TOTAL_JOBS);
PAGE_COUNT = PAGE_COUNT + 10;
serviceCall();
} else {
loading = false;
}
}
}
}
}
});
in this code TOTAL_JOBS : total no of jobs coming from server,
totalItemCount : is the total items in recyclerView ,
set loading = true everytime if there is still response coming for recycleView;

Categories

Resources