Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scroll to particular category position in recyclerview

I want to scroll to item id ==5 after loading recyclerview and I directly set item id in setTargetPosition....Please help me if any one has better clue for it.As per response I want to directly scroll to Sandwich Category after loading recyclerview....

this my setAdapter code;

                try {
                JSONArray jsonArray = arrayList.get(0);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jObj = jsonArray.getJSONObject(i);
                    String catName = jObj.getString("CategoryName");
                    String catId = jObj.getString("CategoryID");
                    Category cat1 = createCategory(catName, Integer.parseInt(catId));
                    JSONArray jProductDetails = jObj.getJSONArray("ProductDetails");
                    ArrayList<HashMap<String, String>> productdetaildata = new ArrayList<HashMap<String, String>>();
                    for (int j = 0; j < jProductDetails.length(); j++) {
                        JSONObject jP = jProductDetails.getJSONObject(j);
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(HitUtilities.product_id, jP.getString("ProductID"));
                        map.put(HitUtilities.product_name, jP.getString("ProductName"));
                        map.put(HitUtilities.product_image, jP.getString("PhotoImagePath"));
                        map.put(HitUtilities.product_price, jP.getString("CurrentPrice"));
                        map.put(HitUtilities.product_isFavorite, jP.getString("Favorited"));
                        productdetaildata.add(map);
                    }
                    cat1.setItemList(createItems(productdetaildata, jProductDetails.length()));
                    catList.add(cat1);
                }

                restaurantMenuAdapter = new RestaurantMenuAdapter(catList);
                rvMenu.setAdapter(restaurantMenuAdapter);

                smoothScroller.setTargetPosition(getPositionWithName("Sandwich"));
                mLayoutManager.startSmoothScroll(smoothScroller);

            } catch (Exception e) {
                e.printStackTrace();
            }

below is my code;

  smoothScroller = new LinearSmoothScroller(RestaurantMenuActivity.this) {
        @Override
        protected int getVerticalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_ANY;
        }
        @Override
        public PointF computeScrollVectorForPosition(int targetPosition) {
            return null;
        }
    };

smoothScroller.setTargetPosition(catList.get(5).getId());
mLayoutManager.startSmoothScroll(smoothScroller);

Below is api response;

   {
  "Status":"Success",
  "StatusCode":"200",
  "Message":"data fetch successfully.",
  "Data":{
  "RestaurantID":"1",
  "ProductCategory":[
     {
        "CategoryID":"1",
        "CategoryName":"Restaurant Offers",
        "No_of_Product":2
     },
     {
        "CategoryID":"2",
        "CategoryName":"Cold Drinks",
        "No_of_Product":4
     },
     {
        "CategoryID":"3",
        "CategoryName":"Pizza",
        "No_of_Product":2
     },
     {
        "CategoryID":"4",
        "CategoryName":"Burger",
        "No_of_Product":1
     },
     {
        "CategoryID":"5",
        "CategoryName":"Sandwich",
        "No_of_Product":2
     },
     {
        "CategoryID":"6",
        "CategoryName":"Chinese",
        "No_of_Product":1
     },
     {
        "CategoryID":"7",
        "CategoryName":"Maxican",
        "No_of_Product":1
     }
  ]
  }
  }
like image 356
Vishal Vaishnav Avatar asked Jan 04 '18 10:01

Vishal Vaishnav


2 Answers

try this code

recyclerView.smoothScrollToPosition(position);
like image 192
Mohit Kalia Avatar answered Oct 26 '22 17:10

Mohit Kalia


Please find working code as below:

    import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView;

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

import java.io.IOException; import java.io.InputStream; import java.util.ArrayList;

public class DemoActivity extends Activity {

private RestaurantMenuAdapter restaurantMenuAdapter;
RecyclerView rvMenu;
private RecyclerView.LayoutManager mLayoutManager;
int sandwichPos;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_demo);
    rvMenu = findViewById(R.id.rvMenu);
    mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
    rvMenu.setHasFixedSize(true);
    rvMenu.setLayoutManager(mLayoutManager);

    try {
        JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
        JSONArray jsonArray = jsonObject.getJSONObject("Data").getJSONArray("ProductCategory");
        ArrayList<Category.CatData> productdetaildata = new ArrayList<Category.CatData>();

        for (int i = 0; i < jsonArray.length(); i++) {
            Category.CatData d = new Category().new CatData();
            JSONObject jObj = jsonArray.getJSONObject(i);
            String catName = jObj.getString("CategoryName");
            String catId = jObj.getString("CategoryID");
            int number = jObj.getInt("No_of_Product");
            d.setCategoryID(catId);
            d.setCategoryName(catName);
            d.setNo_of_Product(number);
            productdetaildata.add(d);
            if(catName.equalsIgnoreCase("Sandwich"))
            {
                sandwichPos = i;
            }
        }

        restaurantMenuAdapter = new RestaurantMenuAdapter(this,productdetaildata);
        rvMenu.setAdapter(restaurantMenuAdapter);
// According to your need you need to change Offset position, Currently it is 20 ((LinearLayoutManager) rvMenu.getLayoutManager()).scrollToPositionWithOffset(sandwichPos, 20); // smoothScroller.setTargetPosition(getPositionWithName("Sandwich")); // mLayoutManager.startSmoothScroll(smoothScroller);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getAssets().open("data.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}
}

///Your adapter is

import android.content.Context; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView;

import java.util.ArrayList;

public class RestaurantMenuAdapter extends RecyclerView.Adapter {

private ArrayList<Category.CatData> objects = new ArrayList<>();

private Context context;
private LayoutInflater layoutInflater;

public RestaurantMenuAdapter(Context context, ArrayList<Category.CatData> objects) {
    this.objects =objects;
    this.context = context;
    this.layoutInflater = LayoutInflater.from(context);
}


@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemCount() {
    return objects.size();
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {


    View view = layoutInflater.inflate(R.layout.adapter_restaurant, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    final Category.CatData model = objects.get(position);
    if (position % 2 == 1) {
        holder.view1.setBackgroundColor(Color.BLUE);
    } else {
        holder.view1.setBackgroundColor(Color.CYAN);
    }
    holder.id.setText(""+model.getCategoryID());
    holder.name.setText(""+model.getCategoryName());
    holder.number.setText(""+model.getNo_of_Product());


}


protected class ViewHolder extends RecyclerView.ViewHolder{
    private TextView id;
    private TextView name;
    private TextView number;
    private LinearLayout view1;

    public ViewHolder(View view) {
        super(view);
        id = (TextView) view.findViewById(R.id.id);
        name = (TextView) view.findViewById(R.id.name);
        number = (TextView) view.findViewById(R.id.number);
        view1 = view.findViewById(R.id.view);
    }
}
}

// Model Class is

import java.util.ArrayList;

public class Category {

ArrayList<CatData> ProductCategory;

public ArrayList<CatData> getProductCategory() {
    return ProductCategory;
}

public void setProductCategory(ArrayList<CatData> productCategory) {
    ProductCategory = productCategory;
}


public class CatData {
    String CategoryID;
    String CategoryName;
    int No_of_Product;

    public String getCategoryID() {
        return CategoryID;
    }

    public void setCategoryID(String categoryID) {
        CategoryID = categoryID;
    }

    public String getCategoryName() {
        return CategoryName;
    }

    public void setCategoryName(String categoryName) {
        CategoryName = categoryName;
    }

    public int getNo_of_Product() {
        return No_of_Product;
    }

    public void setNo_of_Product(int no_of_Product) {
        No_of_Product = no_of_Product;
    }
}
}
like image 29
Patrick R Avatar answered Oct 26 '22 17:10

Patrick R