首页 > android 如何在依赖于activity的一个fragment中传递this参数

android 如何在依赖于activity的一个fragment中传递this参数

我定义了一个activity,有一个leftfragment和一个contentfragment依赖它,现在我要早contentfragment中实现背景滑动效果。
我的fragment继承了

`public class ContentFragment extends BaseFragment implements ListItemClickHelp,GestureDetector.OnGestureListener,

    View.OnTouchListener {`
    
    

下面的变量需要传递this参数

       rl_bg.setOnTouchListener((View.OnTouchListener) this);
        rl_bg.setLongClickable(true);
        mGesture = new GestureDetector((GestureDetector.OnGestureListener) this);

我如果这样传递的话就会报错
Caused by: java.lang.ClassCastException: com.example.hp.pumpkin2.MainActivity cannot be cast to android.view.View$OnTouchListener

就是activity不能转换为我在fragment中继承的接口对象,我就很郁闷,我是需要在contentfragment中实现这些逻辑,不能把这些逻辑放在activity中来实现,但是又需要传递这样的参数,请问我应该怎么做呢?


传this本质上没错,只是你又把this强转了一遍,造成了类型转换异常,应该这么写

rl_bg.setOnTouchListener(this);
rl_bg.setLongClickable(true);
mGesture = new GestureDetector(this);

因为你的fragment都已经实现了OnTouchListener,OnGestureListener接口,这个fragment的this对象就已经包含了两个接口的方法,要使用只需要传this就行了,跟activity没有关系了。this关键字的意义你还需要再去理解了。

【热门文章】
【热门文章】