我一直在努力将这个Kotlin代码翻译成Java,因为该项目是用Java编写的.我正在通过研究Kotlin语法进行翻译.但是,还有一些人我很难理解.
特别:
private val animationView: LottieAnimationView by lazy {
rootView.inflate(R.layout.app_intro_animation_view,false) as LottieAnimationView
}
private val viewPager: LockableViewPager by lazy {
findViewByIdIoUr(): IntroButton.BehavIoUr {
return object : IntroButton.BehavIoUr {
override fun setActivity(activity: IntroActivity) { finish() }
override fun getActivity(): IntroActivity? = null
override fun run() {}
}
}
private fun setViewPagerScroller() {
try {
val scrollerField = ViewPager::class.java.getDeclaredField("mScroller")
scrollerField.isAccessible = true
val interpolator = ViewPager::class.java.getDeclaredField("sInterpolator")
interpolator.isAccessible = true
val scroller = object : Scroller(this,interpolator.get(null) as Interpolator) {
override fun startScroll(startX: Int,startY: Int,dx: Int,dy: Int,duration: Int) {
super.startScroll(startX,startY,dx,dy,duration * 7)
}
}
scrollerField.set(viewPager,scroller)
} catch (e: NoSuchFieldException) {
// Do nothing.
} catch (e: IllegalAccessException) {
// Do nothing.
}
}
对于setViewPagerScroller,我能够翻译第一部分.
Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
scrollerField.setAccessible(true);
Field interpolator = ViewPager.class.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);
最佳答案
setViewPagerScroller方法使用kotlin anonymous inner class语法.这是’对象’部分,它在java语法中没有真正的对应部分.
原文链接:https://www.f2er.com/java/437443.htmlprivate void setViewPagerScroller() {
try {
Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
scrollerField.setAccessible(true);
Field interpolator = ViewPager.class.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);
Scroller scroller = new Scroller(this,(android.view.animation.Interpolator) interpolator.get(null)){
@Override
public void startScroll(int startX,int startY,int dx,int dy,int duration) {
super.startScroll(startX,duration * 7);
}
}
scrollerField.set(viewPager,scroller);
} catch (NoSuchFieldException error) {
// Do nothing.
} catch (IllegalAccessException error) {
// Do nothing.
}
}
as关键字就像java中的一个转换.希望你能用这个翻译有趣的generateFinalButtonBehavIoUr(),它包含更多相同的内容.
毫无疑问,Lazy构造在java中变得更加冗长.如果您选择遵循以下结构,则必须使用规则来错误地访问viewpager.
private LockableViewPager viewPager;
private LockableViewPager getViewPager(){
if(viewPager == null){
// produce viewpager and store in field
}
return viewPager;
}
您还可以使用类来更准确地表示字段的延迟初始化. (这样你就不会错误地访问一个你想要懒惰地初始化的字段)这变得更加冗长但是值得.