Search code examples
javaandroiduser-interfaceandroid-recyclerviewscrollview

ScrollView not scroll smoothly


I am developing online store application, i used bottom navigation menu and fragments to separate the pages of my online store , in my main fragment i have one scrollview that contains one image slider and two horizontal recycler views that used to show newest and special products. every thing id good but

my really strange problem is that when i run application in my android phone the scrollview has really really bad performance, it scrolls really slowly and not smoothly.

i tried many ways to solve this problem ( but unfortunately none of them could solve my problem ) : - i tried to remove image slider library - i taught maybe images and bitmaps are the main cause of this bad performance but after i removed all images nothing changed !!!

and here is my code :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f6f6f6"
android:layoutDirection="rtl"
android:orientation="vertical">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/slider_container"
            android:layout_width="wrap_content"
            android:layout_height="180dp">

            <com.daimajia.slider.library.SliderLayout
                android:id="@+id/slider"
                android:layout_width="match_parent"
                android:layout_height="180dp" />

            <com.daimajia.slider.library.Indicators.PagerIndicator
                android:id="@+id/custom_indicator"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <com.rd.PageIndicatorView
                android:id="@+id/pageIndicatorView"
                app:piv_animationType="worm"
                app:piv_dynamicCount="true"
                app:piv_interactiveAnimation="true"
                app:piv_padding="8dp"
                app:piv_radius="4dp"
                app:piv_selectedColor="@color/golden_vip"
                app:piv_unselectedColor="#d1d1d1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="15dp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/special_products_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:layout_margin="10dp"
                android:background="#f1f1f1">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right|center_vertical"
                    android:layout_marginRight="10dp"
                    android:text="محصولات ویژه وی آی پی"
                    android:textColor="#444444"
                    android:textSize="11sp"
                    android:textStyle="bold" />
            </LinearLayout>

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:src="@drawable/volleyball" />
        </RelativeLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/special_products_horizontal_recyclerview"
            android:layout_width="match_parent"
            android:layout_height="230dp"
            android:layout_below="@+id/special_products_title"
            android:isScrollContainer="false"
            android:nestedScrollingEnabled="false" />

        <RelativeLayout
            android:id="@+id/new_products_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/special_products_horizontal_recyclerview"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:layout_margin="10dp"
                android:background="#f1f1f1">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right|center_vertical"
                    android:layout_marginRight="10dp"
                    android:text="محصولات جدید وی آی پی"
                    android:textColor="#444444"
                    android:textSize="11sp"
                    android:textStyle="bold" />
            </LinearLayout>

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:src="@drawable/volleyball" />
        </RelativeLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/new_products_horizontal_recyclerview"
            android:layout_width="match_parent"
            android:layout_height="230dp"
            android:layout_marginBottom="700dp"
            android:layout_below="@+id/new_products_title"
            android:isScrollContainer="false"
            android:nestedScrollingEnabled="false" />

    </LinearLayout>
</ScrollView>

<RelativeLayout
    android:id="@+id/loader"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:alpha="0.3"
    android:background="#222222"
    android:visibility="visible">

    <ProgressBar
        android:id="@+id/progress_load_categories"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:indeterminate="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progress_load_categories"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:text="لطفا منتظر بمانید ..."
        android:textColor="#ffffff"
        android:textStyle="bold" />
</RelativeLayout>

and here is my fragment :

package com.gladcherry.vipiranian.activityformain;

import android.app.Dialog;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognizerIntent;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import com.github.amlcurran.showcaseview.OnShowcaseEventListener;
import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.targets.ViewTarget;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.gladcherry.vipiranian.Adapter.CategoriesDataAdapter;
import com.gladcherry.vipiranian.Adapter.ProductsDataAdapter;
import com.gladcherry.vipiranian.MaterialSearchViewPersian;
import com.gladcherry.vipiranian.Model.CategoryModel;
import com.gladcherry.vipiranian.Model.DetailsProjectData;
import com.gladcherry.vipiranian.R;
import com.rd.PageIndicatorView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;

/**
 * Created by gladcherry on 9/30/17.
 */

public class MainViPFragment extends Fragment
        implements OnShowcaseEventListener {
    ViewPagerEx.OnPageChangeListener
    Toolbar mToolbar;
    int level = 0;
    GridView gridView;
    private Button inviteButton;
    private static String getCategoriesApiUrl;
    private Dialog loader;
    private Button ChangeCity, EditProfile;
    private ShowcaseView sv;
    private FragmentDrawer drawerFragment;
    private MaterialSearchViewPersian searchView;
    private ProgressBar loadCategories;
    RequestQueue queue;
    TextView textView;
    List<CategoryModel> SliderImages;

    //private PageIndicatorView pageIndicatorView;
    //private SliderLayout sliderLayout;
    private RelativeLayout Loader;
    private List<DetailsProjectData> specialProducts = new ArrayList<>();
    private List<DetailsProjectData> newProducts = new ArrayList<>();
    private ProductsDataAdapter SpecialDataAdapter;
    private ProductsDataAdapter NewDataAdapter;
    private RecyclerView specialRecyclerView; private RecyclerView newRecyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflating view layout

        View layout = inflater.inflate(R.layout.activity_store_categories, container, false);

        makeJsonArrayRequest();
        return layout;
    }

    public void createValidation(String title, String msg) {
        final Dialog builder = new Dialog(getActivity(), R.style.PauseDialog);
        builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
        builder.setTitle(title);
        builder.setContentView(R.layout.dialogforvalidations);
        TextView text = (TextView) builder.findViewById(R.id.error_msg);
        text.setText(msg);
        Button close_dialog = (Button) builder.findViewById(R.id.close_btn_dialog);
        close_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                builder.dismiss();
            }
        });
        // display dialog
        builder.show();
    }

    private void makeJsonArrayRequest() {
        // Get UserId if current user has been registered or logged in
        String UserIdSplash = "";
        SharedPreferences prefs = getActivity().getSharedPreferences("Authentication", MODE_PRIVATE);
        String userId = prefs.getString("UserName", null);
        if (userId != null) {
            UserIdSplash = userId;
        }
        // Get UserId if current user has been registered or logged in

        // Get Guest Guid if Guest has been logged in as guest before
        String GuidSplash = "";
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Authentication", MODE_PRIVATE);
        final String Guid = sharedPreferences.getString("Guid", null);
        if (Guid != null) {
            GuidSplash = Guid;
        }
        // Get Guest Guid if Guest has been logged in as guest before

        //OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
        getCategoriesApiUrl = getResources().getString(R.string.base_url);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getCategoriesApiUrl, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String State = response.get("Status").toString();
                            if (!State.equals("1")) {
                                Loader.animate().alpha(0.0f).setDuration(500);
                                createValidation("  خطای سیستم  ", response.get("Text").toString());
                            } else {
                                Loader.animate().alpha(0.0f).setDuration(500);
                                SliderImages = new ArrayList<>();
                                //pageIndicatorView.setCount(response.getJSONArray("Sliders").length());
                                for (int i = 0; i < response.getJSONArray("Sliders").length(); i++) {
                                    SliderImages.add(
                                            new CategoryModel(
                                                    response.getJSONArray("Sliders").getJSONObject(i).get("Image").toString(),
                                                    "  وی آی پی | ViP ",
                                                    response.getJSONArray("Sliders").getJSONObject(i).get("Id").toString())
                                    );
                                }
JSONArray SpecialProducts = response.getJSONArray("SpecialProducts");
                                for (int i = 0; i < SpecialProducts.length(); i++) {
                                    JSONObject currentProduct = SpecialProducts.getJSONObject(i);
                                    specialProducts.add(new DetailsProjectData(currentProduct.getString("Id"), currentProduct.getString("PersianName"), currentProduct.getString("Image"), currentProduct.get("UnitPrice").toString(), currentProduct.get("PriceWithDiscount").toString(), currentProduct.get("Discount").toString(), "", "", "", ""));
                                }
                                SpecialDataAdapter = new ProductsDataAdapter(getActivity(), specialProducts);
                                LinearLayoutManager layoutManager
                                        = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
                                specialRecyclerView = (RecyclerView) getActivity().findViewById(R.id.special_products_horizontal_recyclerview);
                                specialRecyclerView.setLayoutManager(layoutManager);
                                specialRecyclerView.setAdapter(SpecialDataAdapter);
                                specialRecyclerView.setNestedScrollingEnabled(false);


                                JSONArray NewProducts = response.getJSONArray("NewestProducts");
                                for (int i = 0; i < NewProducts.length(); i++) {
                                    JSONObject currentProduct = NewProducts.getJSONObject(i);
                                    newProducts.add(new DetailsProjectData(currentProduct.getString("Id"), currentProduct.getString("PersianName"), currentProduct.getString("Image"), currentProduct.get("UnitPrice").toString(), currentProduct.get("PriceWithDiscount").toString(), currentProduct.get("Discount").toString(), "", "", "", ""));
                                }
                                NewDataAdapter = new ProductsDataAdapter(getActivity(), newProducts);
                                LinearLayoutManager newlayoutManager
                                        = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
                                newRecyclerView = (RecyclerView) getActivity().findViewById(R.id.new_products_horizontal_recyclerview);
                                newRecyclerView.setLayoutManager(newlayoutManager);
                                newRecyclerView.setAdapter(NewDataAdapter);
                                newRecyclerView.setNestedScrollingEnabled(false);

                   }
                        }
                        catch (Exception ex)
                        {
                            if (ex.getMessage() != null) {
                                Log.d("exception", ex.getMessage());
                            }
                            Loader.animate().alpha(0.0f).setDuration(500);
                        }

                    }
                }, new Response.ErrorListener()

        {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error != null && error.getMessage() != null) {
                    Log.w("VolleyError", error.getMessage());
                    VolleyLog.d(this.getClass().getSimpleName(), "Error: " + error.getMessage());
                }
                //loadCategories.setVisibility(View.GONE);
                createValidation("پیام سیستم", "لطفا اتصال اینترنت خود را بررسی نمایید .");
            }
        });
        request.setRetryPolicy(new

                DefaultRetryPolicy(10000, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue = Volley.newRequestQueue(getActivity().getApplicationContext());
        queue.add(request);

    }

    @Override
    public void onShowcaseViewHide(ShowcaseView showcaseView) {

    }

    @Override
    public void onShowcaseViewDidHide(ShowcaseView showcaseView) {

    }

    @Override
    public void onShowcaseViewShow(ShowcaseView showcaseView) {

    }

    @Override
    public void onShowcaseViewTouchBlocked(MotionEvent motionEvent) {

    }
}

Solution

  • the problem was because of 2 lines that i was added to the manifest to prevent from android out of memory exception ...

    remove these two lines and every thing well be ok :

    android:largeHeap="true" android:hardwareAccelerated="false"

    i hope this answer going to help you ...