1 minute read

5.4. Building and Running the App

Now, let‟s combine these code lines to form our complete MainActivity.java file as follows:

public class MainActivity extends AppCompatActivity {

Advertisement

Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RelativeLayout bgElement = (RelativeLayout) findViewById(R.id.activity_main); bgElement.setBackgroundColor(Color.WHITE); myButtonListenerMethod(); }

public void myButtonListenerMethod() { button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {

RelativeLayout bgElement = (RelativeLayout)findViewById(R.id.activity_main); int color = ((ColorDrawable) bgElement.getBackground()).getColor(); if (color == Color.RED) { bgElement.setBackgroundColor(Color.BLUE); } else { bgElement.setBackgroundColor(Color.RED); }

}

Code 5.9

5.4. Building and Running the App

We have completed both the layout and code development of our first Android app. Let‟s run it by clicking the Run button in Android Studio. I selected a Nexus 4 emulator for running our app on it. The emulator screen when the app is launched is shown in Figure 5.22.

Figure 5.22. The app when it is launched (colour and full resolution figure at the book‟s companion website: www.android-java.website)

As we click on the Change! Button, the background colour changes from red to blue and vice versa as shown in Figure 5.23. We can run this app on a real device as explained in Chapter 3 in detail. I tried this app on an Asus Zenfone 6 and it runs as expected on a real device too.

I hope you enjoyed developing our first programmatic Android app development. If there are question marks about the codes, don‟t worry, I‟m sure you‟ll get used to Android coding in the upcoming chapters.

Small exercise: Could you modify the code to change the label of the button according to the background colour dynamically? If the background colour will be changed to blue, the button text will read Convert to blue! otherwise Convert to red!

Figure 5.23. Our app‟s screen after subsequent button clicks (colour and full resolution figure at the book‟s companion website: www.android-java.website)

This article is from: