【发布时间】:2019-09-09 18:26:36
【问题描述】:
我一直在努力寻找这个问题的解决方案,但我没有。问题是从View返回Activity。 一旦 if 语句变为 false,它应该让我返回 SplashActivity 这里有一些活动和视图类,它们执行应用程序的所有逻辑。
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
GameEngine gameEngine = new GameEngine(this);
setContentView(gameEngine);
}
}
然后我的 SplashActivity 带有一个 ImageButton,一旦按下它就会调用 MainActivity。
public class SplashActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
}
//this method mentioned (onClick) in XML file I've not included.
public void startGame(View view)
{
Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
}
我的视图类:
public class GameEngine extends View
{
boolean inGame;
//Here some code...
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
if(inGame)
{
canvas.drawBitmap(someImage, positionX, positionY, null);
if(positionX > 100)
{
inGame = false;
//Here I want to return to SplashActivity, where my ImageButton is!
}
}
}
}
我不知道如何实现返回 Activity 并从初始点开始使用我的应用程序的想法。 提前致谢!
编辑
这个信息不重要!
最初我更改了代码以提高可读性以触及要点。
这是正在更新的内部类:
public static class Drawable
{
private int x;
private int y;
Drawable(int x, int y)
{
this.x = x;
this.y = y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
void update() {
x -= 3;
}
}
这就是 myobjects 的实际绘制方式
for (Drawable drawable : drawables)
{
//Draw upper pipe
canvas.drawBitmap(pipeUp, drawable.getX(), drawable.getY(), null);
//Draw lower pipe
canvas.drawBitmap(pipeBot, drawable.getX(), drawable.getY() +
pipeUp.getHeight() + GAP, null);
}
这是它的更新方式
private void animation()
{
for(Drawable drawable : new ArrayList<>(drawables))
{
drawable.update();
if(drawable.getX() == dWidth/3 + dWidth/3)
{
drawables.add(new Drawable(pipeX, (int)(Math.random() *
(pipeUp.getHeight() -((pipeUp.getHeight() * 0.25))) - (pipeUp.getHeight() - (pipeUp.getHeight() * 0.25)))));
}
if(drawable.getX() <= 0 - pipeBot.getWidth())
{
drawables.remove(drawable);
}
}
}
然后我在onDraw方法中调用animation()。
【问题讨论】:
-
在
onDraw内部进行昂贵的操作不是很好的做法,也许您可以找到更好的方法来实现这一点。 -
@devgianlu 可能是,但这是我知道的唯一方法
-
你可以在
positionX更新的地方做到这一点。你能发布那个代码吗? -
您可以尝试使用类似于github.com/greenrobot/EventBus 的东西(或任何其他具有观察者模式的方法。关于您可以在此处阅读的模式sourcemaking.com/design_patterns/observer )发布事件 - 在您的主要活动中捕获它并执行你想要的任何动作。但请记住 onDraw - 在视图生命周期中调用了很多次的方法。希望这会有所帮助
标签: java android android-activity view