To achieve an interactive app, we will do three things:
setContentView
from the onCreate
method to show the progress of our UI when we run the appsetContentView
on a different layout (that we have yet to design)As we will be building a ConstraintLayout
and a TableLayout,
we will call our new methods loadConstraintLayout
and loadTableLayout
, respectively.
Let's do that now, and then we can see how we can add some buttons that call these methods alongside some neatly formatted text.
Inside the onCreate
method, add the following highlighted code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
}
The code uses the setContentView
method to load the UI we are currently working on. You can now run the app to see the following results:
Add these two new methods inside the MainActivity
class after the onCreate
method:
void loadConstraintLayout(View v){ setContentView(R.layout.activity_main); } void loadTableLayout(View v){ setContentView(R.layout.my_table_layout); }
There is one error with the first method and two with the second. The first we can fix by adding an import
statement so that Android Studio is aware of the View
class. Left-click the word View
to select the error. Hold down the Alt key and then tap the Enter key. You will see the following pop-up:
Chose Import class. The error is gone. If you scroll to the top of the code, you will see that a new line of code has been added by that shortcut we just performed. Here is the new code:
import android.view.View;
Android Studio no longer considers the View
class an error.
The second method still has an error, however. The problem is that the method calls the setContentView
method to load a new UI (R.layout.my_table_layout
). As this UI layout does not exist yet, it produces an error. You can comment out this call to remove the error until we create the file and design the UI layout later this chapter. Add the double forward slash//
as highlighted next:
void loadConstraintLayout(View v){
setContentView(R.layout.activity_main);
}
void loadTableLayout(View v){
// setContentView(R.layout.my_table_layout);
}
Now we want to add some buttons, that we can click to call our new methods and load the new layouts we will be building soon. But adding a couple of buttons with some text on is too easy—we have done that before. What we want to do is line up some text with a button to the right of it. The problem is that our LinearLayout
has the orientation
attribute set to vertical
and, as we have seen, all the new parts we add to the layout will be lined up vertically.
18.226.165.247