我一直试图找到这个问题的解决方案,但我没有。问题是从View返回Activity。如果if语句变为false,它应该将我返回到SplashActivity这里的一些Activities和View类,它们执行所有应用程序逻辑。
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
GameEngine gameEngine = new GameEngine(this);
setContentView(gameEngine);
}
}
然后使用一个ImageButton进行我的SplashActivity,一旦按下它就会调用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的想法并从初始点开始使用我的应用程序。提前致谢!
编辑
这个信息不是重点!
Innitialy我更改了代码,以便更好地阅读主要内容。
这是内部类,它正在更新:
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()。
你可以试试:
Intent mainIntent = new Intent(getContext(), SplashActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
getContext().startActivity(mainIntent);
或者您可以在GameEngine的构造函数中保存MainActivity的引用并使用它来打开splash:
GameEngine gameEngine = new GameEngine(this);
或者您可以实现具有基本存储库模式的livingata:
public class DataRepository {
public static MutableLiveData<Boolean> openSplash = new MutableLiveData<>();
}
在MainActivity上:
DataRepository.openSplash.observe(this, aBoolean -> {
if(aBoolean){
//open splash
}else{
//
}
});
在游戏引擎上:
DataRepository.openSplash.postValue(true);