You will most likely have an object extending Activity for each screen in your app. An activity is responsible for creating a view and coordinate interaction and state. If you are familiar with the MVC pattern, you can think of an activity as a controller. It displays some model state in one or more views and updates the model from events from the views. You can override methods to be notified when your activity is created, stopped, resumed, and destroyed.
An example is onCreate(): Here you should create all the components for your activity and call setContentView() to define layout for the user interface.
publicclassMainActivityextendsActivity{privateEditTextinputField;privateButtonsearchButton;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);// Bind layout XML-filesetContentView(R.layout.activity_main);// Bind UI elementsinputField=(EditText)findViewById(R.id.input_field);searchButton=(Button)findViewById(R.id.search_button);// Set click listenersearchButton.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){StringsearchText=inputField.getText().toString();if(searchText!=null||!searchText.trim().equals("")){// Do something}}});}}
Declare activities in the manifest
You must declare all your activities in the AndroidManifest.xml file, which is the application's contract.
Intents are Android's way of communicating between both activities belonging to other applications and an application's own activities.
In order for other applications to activate your activity, you must list up which intents the activity listens for using intent filters.
The above intent filter exists for most applications, as it describes for the system which activity will be launched when the user first opens the application.
Taking a picture is a task which is delegated to the native camera application by using intens.
// create Intent to take a picture and return control to the calling applicationIntentintent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);intent.putExtra(MediaStore.EXTRA_OUTPUT,someExistingFileUri);// set the image file name// start the image capture IntentstartActivityForResult(intent,CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);/** you determine your own request code, which is laterused in onActivityResult() in order to know which action was performed by the external activity */
You switch between in-app activitivities by using intents in the following way:
To listen to user interaction, you register listeners to the clickable view elements. You can do this in one of two ways, either by attaching the handler manually in code, or by pointing to the handler method from the layout file.
Programmatically:
ButtonbtnExample=(Button)findViewById(R.id.btnExample);btnExample.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){// Do something here }});