在recyclerview中滚动到特定类别位置

时间:2018-01-04 10:20:04

标签: android android-recyclerview recycler-adapter

我想在加载recyclerview之后滚动到项目ID == 5,我直接在setTargetPosition中设置项目ID ....如果有任何人有更好的线索,请帮助我。根据我的回复,我想要加载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 个答案:

答案 0 :(得分:4)

试试这段代码

recyclerView.smoothScrollToPosition(position);

答案 1 :(得分:4)

请找到如下工作代码:

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

答案 2 :(得分:3)

使用SNAP_TO_START更改SNAP_TO_ANY

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

答案 3 :(得分:3)

  

这有助于提高回收者视图滚动的速度和你   可以直接跳到所需的位置。

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

SpeedyLinearLayoutManager.class

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

答案 4 :(得分:3)

更改此代码

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)

答案 5 :(得分:2)

请使用此代码

首先,您可以存储id = 5值的索引,然后将recyclerview滚动到该位置。

recyclerView.scrollToPosition(5);

答案 6 :(得分:2)

在reclerviewview正确加载后尝试滚动到位置,给它一些延迟。

所以你的代码是:

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

我在expandableListView中使用偏移滚动到某个位置遇到了类似的问题。

答案 7 :(得分:2)

您需要添加以下行

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

在你的情况下为我工作,你需要添加所需类别的位置

答案 8 :(得分:0)

您需要包含此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)

现在你可以平滑滚动到你想要的任何位置;)尝试一下。

mRecyclerView.smoothScrollToPosition(5)

答案 9 :(得分:0)

我按照以下方式完成工作;

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