CHAPTER 5. ANDRIOD APP #1: RED/BLUE LIGHTHEAD
Now, let‟s combine these code lines to form our complete MainActivity.java file as follows: public class MainActivity extends AppCompatActivity { 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. 107