I am new to Android GameActivity (Java + C++). I am trying to creating an app with GameActivity template in Android studio. When I run the app, the window shows UI from native C++ (NDK) automatically. And I want to use UI from Views(Java) , a xml layout not C++, to create some buttons. When the user clicked the button, switch back to native C++ UI(which is not a layout).
Here is what I did to set the content view:
//Template generated "MainActivity" class extended from "GameActivity" class
static {
System.loadLibrary("Native");
}
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.layout); //I added this line, set the window to xml layout
}
But now I cannot find the way to set the window content back to Native C++ UI.
I have tried to use setVisibility()
to View.GONE
as what this official documentation said.
//inside OnCreated() method
setContentView(R.layout.layout);
//I didn't wait for button clicked event because this is just testing
View contentView = findViewById(R.id.mainview);//Top level Layout in xml
contentView.setVisibility(View.GONE);
and the whole window became black. So it seems like the R.layout.layout
is still there but nothing visible. How do I switch the window back to Native C++ automatically generate by template?
I will assume you use the default code generated from template. This template is making use of GameActivity
class. When you create a project with this template then your main activity will extend from GameActivity
class. With Android Studio you can navigate to it, and see what it does. Among, others, you will see it creates its own layout with this code:
this.mSurfaceView = new InputEnabledSurfaceView(this);
FrameLayout frameLayout = new FrameLayout(this);
this.contentViewId = ViewCompat.generateViewId();
frameLayout.setId(this.contentViewId);
frameLayout.addView(this.mSurfaceView);
this.setContentView(frameLayout);
frameLayout.requestFocus();
this.mSurfaceView.getHolder().addCallback(this);
ViewCompat.setOnApplyWindowInsetsListener(this.mSurfaceView, this);
So if yout call setContentView
in your code you delete all above work from GameActivity - this way remove the SurfaceView where game is rendered.
To add your own layout you need to add it to the FrameLayout from the base class. You can use below code for this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// contentViewId is defined in GameActivity
val rootView = findViewById<View>(contentViewId);
// my_layout.xml is you custom layout file
val myLayout = layoutInflater.inflate(R.layout.my_layout, rootView as ViewGroup, false)
rootView.addView(myLayout)
myLayout.visibility = View.VISIBLE // or View.GONE to hide it
}