Java-从单独的类打开新视图
现在我有了扩展Activity类的MainActivity.javaJava-从单独的类打开新视图,java,android,view,android-activity,Java,Android,View,Android Activity,现在我有了扩展Activity类的MainActivity.java package com.divergent.tapdown1; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override public void o
package com.divergent.tapdown1;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View PlayScreen = new PlayScreen(this);
setContentView(PlayScreen);
PlayScreen.setBackgroundColor(Color.BLACK);
}
}
这将打开扩展视图的PlayScreen。
当某个事件发生时,我希望能够打开从PlayScreen创建的新LoseScreen。问题在于setContentView()显然是Activity类的一部分。我怎样才能避开这件事
谢谢
编辑:
if(playerBounds.bottom>rowBlock.top&&playerBounds.topblockX2[row])){
ViewGroup parent=(ViewGroup)getParent();
最终得分=分数;
addView(新的PauseScreen(getContext());
parent.bringToFront();
父.setBackgroundResource(R.drawable.pausebackground);
}
您可以采取以下几种方法:
- 您可以创建一个容器视图(例如,
),将其用作根视图,并向其中添加LoseScreen,然后从中删除PlayScreen。如果其他代码需要添加/删除视图,则可以传递对容器的引用FrameLayout
View playScreen = new PlayScreen(this); View container = new FrameLayout(this); playScreen.setRootView(container); container.addView(playScreen); setContentView(container);
- 您可以将对
的引用传递给创建屏幕的类。由于MainActivity
是一个公共方法,因此您可以在其上调用setContentView
,例如:setContentView
然后从Activity mainActivity = this; playScreen.setMainActivity(mainActivity);
播放屏幕中:
mainActivity.setContentView(new LoseScreen(getContext()));
- 在
中,您可以使用PlayScreen
获得父视图,然后,与第一种方法类似,将LoseScreen添加到其中并移除PlayScreengetParent()
ViewGroup parent = (ViewGroup)getParent(); parent.addView(new LoseScreen(getContext())); parent.removeView(this);
ViewGroup parent = (ViewGroup)getParent();
parent.addView(new LoseScreen(getContext()));
parent.removeView(this);