我需要访问使用第三方库创建的 RecyclerView
的方法。
我正在做的是使用 findViewById 获取 RecyclerView
View :
ViewGroup mainView = mainActivity.getWindow().getDecorView().findViewById(android.R.id.content);
if(feedView == null){
Object okStreamRecyclerView = mainView.findViewById(NEWSFEED_RECYCLER_ID);
feedView = (okStreamRecyclerView.getClass().getSuperclass()).getSuperclass();
scrollToTop(feedView);
}
此时 feedView.getSimpleName
结果为 RecyclerView
。然后我尝试使用以下方法将此 RecyclerView
滚动到顶部:
private void scrollToTop(Class feedView) {
log("THE VIEW IS OF TYPE: "+feedView.getName()); // androidx.recyclerview.widget.RecyclerView
try {
Method method = feedView.getMethod("getLayoutManager");
method.setAccessible(true);
LinearLayoutManager layoutManager = (LinearLayoutManager) method.invoke(feedView);
layoutManager.scrollToPositionWithOffset(0, 0);
} catch (NoSuchMethodException e) {
log("NO SUCH METHOD EXCEPTION",e);
} catch (IllegalAccessException e) {
log("ILLEGAL ACCESS EXCEPTION",e);
} catch (InvocationTargetException e) {
log("INVOCATION TARGET EXCEPTION",e);
}
}
但由于某种原因我收到以下错误:
IllegalArgumentException: Expected receiver of type androidx.recyclerview.widget.RecyclerView, but got java.lang.Class<androidx.recyclerview.widget.RecyclerView>
如何将类转换为预期的 RecyclerView
?还有其他方法可以获取此 View 吗?
最佳答案
感谢@CommonsWare提示,我成功地使用反射调用了ScrollToPosition
方法。这是我的具体情况下的工作代码,在其他情况下可能会更容易:
View okStreamRecyclerView = null;
try {
okStreamRecyclerView = mainView.findViewById(NEWSFEED_RECYCLER_ID);
feedView = (okStreamRecyclerView.getClass().getSuperclass()).getSuperclass();
Method method = feedView.getMethod("getLayoutManager");
method.setAccessible(true);
LinearLayoutManager layoutManager = (LinearLayoutManager) method.invoke(okStreamRecyclerView);
Class llm = layoutManager.getClass().getSuperclass();
Method m2 = llm.getMethod("scrollToPositionWithOffset",int.class, int.class);
m2.setAccessible(true);
m2.invoke(layoutManager,0,0);
} catch (ClassCastException e){
log("AN EXECPTON OCCURED WHILE FETCHING VIEW",e);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
关于java - 从使用反射获得的 RecyclerView 调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56633995/