我想访问在GestureListener
本身的方法中使用gestureListener的视图。
这是我的倾听者:
public class GestureSwipeListener extends SimpleOnGestureListener {
final Context myContext;
// Costanti per lo swipe
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
public GestureSwipeListener(Context context) {
myContext = context;
}
@Override
public boolean onDown(MotionEvent e) {
return super.onDown(e);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD
&& Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
}
} else {
if (Math.abs(diffY) > SWIPE_THRESHOLD
&& Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
public boolean onSwipeRight() {
Log.d("FLING", "right");
return true;
}
public boolean onSwipeLeft() {
Log.d("FLING", "left");
return true;
}
public boolean onSwipeTop() {
Log.d("FLING", "top");
return true;
}
public boolean onSwipeBottom() {
Log.d("FLING", "bottom");
return true;
}
} // end class OnSwipeTouchListener
然后在我的活动中我这样做:
GestureSwipeListener gestureListener = new GestureSwipeListener(this);
GestireDetector gestureDetector = new GestureDetector(getApplicationContext(), gestureListener);
mainView = findViewById(R.id.main_view);
mainView.setClickable(true);
mainView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
});
现在我想直接在GestureSwipeListener
内部获取视图资源(在本例中为mainView),以便在该视图上执行一些动画。
我想这样做是因为我必须在我的应用程序中的每个Activity上重复相同的动画。因此,直接在GestureListener
中使用代码(在onSwipeRight
,onSwipeLeft
方法中)最好避免重复使用相同的代码。
我怎么能这样做?
答案 0 :(得分:6)
将参数添加到SwipeGestureListener构造函数中,如:
在你的gestureListener中:
View myView;
public GestureSwipeListener(Context context, View view) {
myContext = context;
myView = view;
}
public doSomethingWithView() {
this.myView.setText("Foobar");
}
在您的活动中:
GestureSwipeListener gestureListener = new GestureSwipeListener(this.appContext, mainView);
...
更新1:
View mainView = findViewById(R.id.main_view);
GestureSwipeListener gestureListener = new GestureSwipeListener(this.appContext, mainView);
然后不要忘记你的GestureSwipeListener构造函数:
View myView;
public GestureSwipeListener(Context context, View view) {
myContext = context;
myView = view;
}