可能重复:
What is the right way to communicate from a custom View to the Activity in which it resides?
我还是Java新手。
我想制作一个滑块类。我希望这个类可以处理所有滑动机制,并且可以抽象出滑块内完成的操作。
主要代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentLayout(R.layout.slider_page);
slide = (Slider) findViewById(R.id.slider);
slide.addSlide(R.drawable.slide_blue);
slide.addSlide(R.drawable.slide_green);
/* I want to implement the following three functions */
slide.touched () {
text.setText("Slider touched")
// Do stuff
}
slide.onSwipeRight() {
text.setText("Swipe right detected");
// do more stuff
}
slide.touchReleased() {
text.setText("Slider released");
// more stuff
}
}
Slider.java:
public class Slider extends ViewFlipper implements OnTouchListener {
private int SWIPE_MIN_DISTANCE = 100;
private int DOWNTIME_MAX = 300;
private int SWIPETIME_MAX = 870;
private Context mContext;
private float xDownPos;
public Slider(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
this.setOnTouchListener((OnTouchListener) mContext);
}
public void addSlide (int resId) {
ImageView iv = new ImageView(mContext);
iv.setImageResource(resId);
this.addView(iv);
}
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
// store the X value when the user's finger was pressed down
xDownPos = event.getX();
/* How do I get this to return to touched () in the main code? */
break;
}
case MotionEvent.ACTION_UP:
{
// Get the X value when the user released his/her finger
float currentX = event.getX();
float horizontalMovement = currentX - xDownPos;
long timePressed = event.getEventTime() - event.getDownTime();
// Left to Right
if (horizontalMovement > SWIPE_MIN_DISTANCE && timePressed < SWIPETIME_MAX)
{
/* How do I return this to onSwipeRight() in main code? */
}
/* How do I return this to touchReleased() in main code? */
break;
}
}
}
所以,基本上,我想在main中实现touch(),onSwipeRight()和touchReleased()段的代码,并尝试让Slider.java向main发送某种信号。这样做。