[英]Invoking a method from a RecyclerView obtained using reflection
I need to access the methods of a RecyclerView
that is created using a third party library. 我需要访问使用第三方库创建的
RecyclerView
的方法。 What I'm doing is to get hold of the RecyclerView
View using the findViewById: 我正在做的是使用findViewById掌握
RecyclerView
视图:
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);
}
At this point feedView.getSimpleName
results in RecyclerView
. 此时,
feedView.getSimpleName
RecyclerView
。 Then I'm trying to scroll this RecyclerView
to the top using: 然后,我尝试使用以下命令将此
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);
}
}
but for some reason I get the error bellow: 但由于某种原因,我得到以下错误:
IllegalArgumentException: Expected receiver of type androidx.recyclerview.widget.RecyclerView, but got java.lang.Class<androidx.recyclerview.widget.RecyclerView>
How can I convert the Class to the expected RecyclerView
? 如何将类转换为预期的
RecyclerView
? Is there any other way to get hold of this view ? 还有其他方法可以掌握这种观点吗?
Thanks to @CommonsWare hint I managed to invoke the ScrollToPosition
method using reflection. 感谢@CommonsWare提示,我设法使用反射调用了
ScrollToPosition
方法。 Here is the working code in my specific case, it might be easier in some other scenario: 这是我的特定情况下的工作代码,在其他情况下可能会更容易:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.