正在研发a related view I'm attempting to build ,我开始了一个简单的项目,以便在超越自己之前掌握如何做更多基本的绘图“东西”。
就像我的其他问题所述,有很多有关 SurfaceView 线程和动画的信息,但我觉得对于这个应用程序来说,这可能有点过头了。我将同时在屏幕上显示 10 个甚至数百个最终 View ,根据我收集的有关 SurfaceView 的信息,它通常用作 Activity 的主视图(游戏屏幕等)。
这个研发应用程序绘制了几个圆圈,并计算目标(红线)和先前位置(白线)之间的距离:
我的 onDraw
非常简单,但我很难弄清楚如何实现线程或处理程序,或任何类型的非 UI 循环来计算目标之间的值和主圈。
我有一个私有(private)静态内部线程,我认为这很容易,但没有骰子。最新的弗兰肯密码:
private static class DragThread extends Thread {
private DragTest view;
private boolean animate;
private float currentY, targetY, delta, inc;
public DragThread(View v){
view = (DragTest)v;
targetY = view.mTargetData.getY();
currentY = view.mMainData.getY();
}
public void run(){
while(Math.abs(currentY - targetY) >= 0){
view.mMainData.setY(currentY + 10f);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}finally{
view.postInvalidate();
}
}
Log.e(TAG, "Loop finished");
}
}
mMainData
和 mTargetData
只是保存每个圆的位置值的 POJO,我的 onDraw 使用它来更新位置:
mMainData = new CircleData(startXposition, startYposition, radius);
...并使用标准 getter 进行检索。
本质上,我知道当我抬起手指时我需要启动循环逻辑,但我遇到了一些错误,从“线程已经启动”到卡住和崩溃。处理人员给我泄漏警告......伙计。我已经精疲力尽了
这是我的 View 的 onTouchEvent
,其中包含每个事件的说明:
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if(action == MotionEvent.ACTION_DOWN){
// set some flags for drawing, update "hero" circle Y position
// based off event data
}else if(action == MotionEvent.ACTION_UP){
// reset flags that dictate ghost circle drawing, etc. and invalidate
// I think I need to start the loop here, but how?!
// new Thread().start()? Some sort of Handler? GAH!
}else if(action == MotionEvent.ACTION_MOVE){
// update mMainData Y position which is passed into onDraw, invalidate to reflect movement changes
}
return false;
}
最佳答案
基于this article ,解决方案显然就在我面前,但我认为它比实际情况更难。
相关示例应用程序的最终解决方案是让 View 实现 Runnable,在用户抬起手指时设置一个新的动画Thread
,并使用 Scroller
来计算偏移量。
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if(action == MotionEvent.ACTION_DOWN){
// ...
}else if(action == MotionEvent.ACTION_UP){
// ...
startAnimation();
return true;
}else if(action == MotionEvent.ACTION_MOVE){
// ...
}
return false;
}
public void run(){
int start = (int)mMainData.getY();
int end = (int)mTargetData.getY();
mScroller.startScroll(0, start, 0, -Math.round(mMainData.getY() - end), 500);
while(canAnimate()){
while(mScroller.computeScrollOffset()){
mMainData.setY(mScroller.getCurrY());
postInvalidate();
}
stopAnimation();
}
}
private void startAnimation(){
mThread = new Thread(this);
mThread.start();
}
private void stopAnimation(){
animate = false;
}
private boolean canAnimate(){
return animate == true;
}
关于android - 动画 View 中的线程...如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12995963/