我想访问在方法中使用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
Run Code Online (Sandbox Code Playgroud)
然后在我的活动中我这样做:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
现在我想直接在GestureSwipeListener视图内部获取视图资源(在本例中为mainView),以在该视图上执行一些动画.
我想这样做是因为我必须在我的应用程序中的每个Activity上重复相同的动画.因此,使用的代码直接在GestureListener(在onSwipeRight,onSwipeLeft 方法)可以连连避免相同的代码的重复更好.我怎样才能做到这一点?
将参数添加到SwipeGestureListener构造函数中,如:
在你的gestureListener中:
View myView;
public GestureSwipeListener(Context context, View view) {
myContext = context;
myView = view;
}
public doSomethingWithView() {
this.myView.setText("Foobar");
}
Run Code Online (Sandbox Code Playgroud)
在您的活动中:
GestureSwipeListener gestureListener = new GestureSwipeListener(this.appContext, mainView);
...
Run Code Online (Sandbox Code Playgroud)
更新1:
View mainView = findViewById(R.id.main_view);
GestureSwipeListener gestureListener = new GestureSwipeListener(this.appContext, mainView);
Run Code Online (Sandbox Code Playgroud)
然后不要忘记你的GestureSwipeListener构造函数:
View myView;
public GestureSwipeListener(Context context, View view) {
myContext = context;
myView = view;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3565 次 |
| 最近记录: |