прокрутка до определенной позиции категории в recyclerview

Я хочу прокрутить до item id ==5 после загрузки recyclerview, и я напрямую устанавливаю item id в setTargetPosition....Пожалуйста, помогите мне, если у кого-нибудь есть ключ к этому.В соответствии с ответом я хочу сразу перейти к категории сэндвича после загрузки recyclerview....

Это мой код setAdapter;

                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();
            }

ниже мой код;

  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);

Ниже приведен ответ api;

   {
  "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
     }
  ]
  }
  }

10 ответов


попробуйте этот код

recyclerView.smoothScrollToPosition(position);

пожалуйста, найдите рабочий код, как показано ниже:

    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;
}
}

///адаптер

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);
    }
}
}

// модель класс

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;
    }
}
}

измените SNAP_TO_ANY с помощью SNAP_TO_START

RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
  @Override protected int getVerticalSnapPreference() {
    return LinearSmoothScroller.SNAP_TO_START;
  }
};

получить позицию с категории

public int getPositionWithName(String searchCatPos)
{
    int i=0;
    for(Category cat:catList)
    {
        if(cat.categoryName.equalsIgnoreCase(searchCatPos))
        {
             return i;

        }
        i++;
    }

    return 0;
}

получить положение адаптера и setTargetPosition и свиток

smoothScroller.setTargetPosition(getPositionWithName("Sandwich"));
((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(getPositionWithName("Sandwich"), 20);

Это поможет увеличить скорость прокрутки просмотра recycler и вы можете сразу перейти к нужной позиции.

SpeedyLinearLayoutManager linearLayoutManager = new SpeedyLinearLayoutManager(MainActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
linearLayoutManager.scrollToPosition(myPosition);   // Position to scroll recycler view.      
myRecyclerView.setLayoutManager(linearLayoutManager);

SpeedyLinearLayoutManager.класс!--4-->

 public class SpeedyLinearLayoutManager extends LinearLayoutManager {

        private static final float MILLISECONDS_PER_INCH = 2f; //default is 25f (bigger = slower)

        public SpeedyLinearLayoutManager(Context context) {
            super(context);
        }

        public SpeedyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }

        public SpeedyLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }

        @Override
        public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {

            final LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {

                @Override
                public PointF computeScrollVectorForPosition(int targetPosition) {
                    return SpeedyLinearLayoutManager.this.computeScrollVectorForPosition(targetPosition);
                }

                @Override
                protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                    return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
                }
            };

            linearSmoothScroller.setTargetPosition(position);
            startSmoothScroll(linearSmoothScroller);
        }
    }

изменить этот код

String catName = jObj.getString("CategoryName");
String catId = jObj.getString("CategoryID");

такой

String catName = jObj.getString("CategoryName");
if(catName.equals("Sandwich"){
  SandwichPosition=j
}
String catId = jObj.getString("CategoryID");

и после установки recyclerview, вызовите

mLayoutManager.scrollToPositionWithOffset (SandwichPosition,0)

пожалуйста, используйте этот код

во-первых, вы можете индекс, где хранится значение id=5, затем прокрутите recyclerview до этой позиции.

recyclerView.scrollToPosition(5);

попробуйте прокрутить до позиции после правильной загрузки recyclerview, предоставив ему некоторую задержку.

таким образом, ваш код будет:

recyclerview.postDelayed(new Runnable() {
        @Override
        public void run() {
            recyclerview.scrollToPosition(5);
        }
    },500);

я столкнулся с аналогичной проблемой при прокрутке до некоторой позиции со смещением в expandableListView.


вам нужно добавить под строкой

rvChat.scrollToPosition(chatAdapter.getItemCount() - 1);

работал на меня в вашем случае вам нужно добавить позицию требуемой catagory


вам нужно включить этот класс customLinearLayoutManager:

class CustomLinearLayoutManager(context: Context) : LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) {

    override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State?, position: Int) {
        val smoothScroller = TopSnappedSmoothScroller(recyclerView.context)
        smoothScroller.targetPosition = position
        startSmoothScroll(smoothScroller)
    }


    private inner class TopSnappedSmoothScroller(context: Context) : LinearSmoothScroller(context) {

        override fun computeScrollVectorForPosition(targetPosition: Int): PointF? = this@CustomLinearLayoutManager.computeScrollVectorForPosition(targetPosition)

        override fun getVerticalSnapPreference(): Int = LinearSmoothScroller.SNAP_TO_START

        override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float = MILLISECONDS_PER_INCH / displayMetrics.densityDpi
    }

    companion object {
        private const val MILLISECONDS_PER_INCH = 80f
    }

}

установите RecyclerView layoutManager:

mRecyclerView.layoutManager = CustomLinearLayoutManager(ctx)

и теперь вы можете smoothScroll в любую позицию, которую вы хотите;) попробуйте.

mRecyclerView.smoothScrollToPosition(5)

Я достигаю своей работы следующим образом;

забрать LinearLayoutManager

LinearLayoutManager mLayoutManager = new LinearLayoutManager(RestaurantMenuActivity.this);
rvMenu.setLayoutManager(mLayoutManager);

и прокрутите до позиции, как показано ниже кода;

   int scrollPosition = 0;
    for (int j = 0; j < pos; j++) {
        scrollPosition += menuItem.getData().getProductCategory().get(j).getProductDetails().size();
        scrollPosition++;
    }
    mLayoutManager.scrollToPosition(scrollPosition);
    final Handler handler = new Handler();
    final int finalScrollPosition = scrollPosition;
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            View rclItemView = rvMenu.getChildAt(0);
            mLayoutManager.scrollToPositionWithOffset(finalScrollPosition, rclItemView.getBaseline());
        }
    }, 100);