我正在尝试使Recyclerview中的项目在向上或向下滚动时移动,这取决于子视图的Y坐标。但是,我似乎无法获得孩子们的坐标。 如何获得Y坐标? 我在onBindViewHolder方法中需要它,以便我可以根据它设置子视图的布局参数。
答案 0 :(得分:0)
在您的活动/片段中:
RecyclerView yourRecyclerView;
FansAdapter yourRecyclerAdapter;
........
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
yourRecyclerView.setLayoutManager(new LinearLayoutManager(this));
yourRecyclerView.setHasFixedSize(true);
yourRecyclerAdapter = new YourAdapter (populateYourList(), this);
yourRecyclerView.setAdapter(yourRecyclerAdapter);
yourRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
View firstVisibleChild = recyclerView.getChildAt(0);//change if necessary. determine that item(items) you need to find
final ImageView imageView = (ImageView) firstVisibleChild.findViewById(R.id.item_image);
if (null != imageView) {
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int[] locationsFrom = new int[2];
imageView.getLocationInWindow(locationsFrom);
int xStart = locationsFrom[0];
int yStart = locationsFrom[1];
Log.d("LOG_TAG", "your item xEnd=" + xStart +" yEnd=" + yStart);
if (null != yourRecyclerAdapter) {
yourRecyclerAdapter.setX(xStart);
yourRecyclerAdapter.setY(yStart);
}
}
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != yourRecyclerView) {
yourRecyclerView.clearOnScrollListeners();
}
}
和适配器:
public class YourAdapter extends RecyclerView.Adapter<YourAdapter.YouViewHolder> {
ArrayList<String> fansList;
Context mContext;
private int x;
private int y;
public YourAdapter(ArrayList<String> fansList, Context context) {
this.fansList = fansList;
this.mContext = context;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
@Override
public YouViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (viewGroup instanceof RecyclerView) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycle_item_fans, viewGroup, false);
view.setFocusable(true);
return new YouViewHolder(view);
} else {
throw new RuntimeException("Not bound to RecyclerView");
}
}
@Override
public void onBindViewHolder(YouViewHolder holder, int position) {
holder.itemName.setText(fansList.get(position));
Log.v("LOG_TAG","x="+x+" y="+y);// use y or x
}
@Override
public int getItemCount() {
return fansList.size();
}
//holder
public final class YouViewHolder extends RecyclerView.ViewHolder {
public final TextView itemName;
public final ImageView imageView;
public YouViewHolder(View rowView) {
super(rowView);
this.itemName = (TextView) rowView.findViewById(R.id.text_fan_name);
this.imageView = (ImageView) rowView.findViewById(R.id.image_second_free);
}
}
}