First Android App

  • User interfaces in android are called “layouts”. Android Studio comes with graphical layout editor but under the hood these are xml files.

  • Each element can be given a custom id which can be referenced in Java code.

    TextView homeText = findViewById(R.id.home_text);
    homeText.setText("Hello!"); 
    • Here id is not referenced by home_text as we wrote in home layout (the graphical xml file) but id is referenced by R.id.home_text. The resource reference class R is automatically generated based on various resources, including the IDs referenced in the layout xml file.

If you run into findViewById() crashes, go back to the layout editor and make sure the ID home_text is really set on the TextView element.

Handling Button clicks.

Button homeButton = findViewById(R.id.home_button);
homeButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.v("HEXTREE", "Button has been clicked!");
    }
});
  • Here button is referenced by R.id.home_button and an OnClickListener() event is specified which handles what will happen when button is clicked.

The official android documentation :-

Android Mobile App Developer Tools – Android Developers

Sending Intents

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("<https://hextree.io/>"));
startActivity(browserIntent);
  • Here browserIntent intent creates a new intent with ACTION_VIEW to the url https;//hextree.io .

  • It will be handles by Chrome as chrome’s AndroidManifest.xml contains this which specifies that it can handle ACTION_VIEW and the protocol (https) is also supported :-

Chrome’s AndroidManifest.xml file :- AndroidManifest.xml

Receive Intents

  • First we have to export an activity so that they can be started by other applications.

  • After that we also have to add intent filter in that activity so that it can receive that intent.(In AndroidManifest.xml)

<intent-filter>
    <action android:name="android.intent.action.SEND" />
    <data android:mimeType="text/plain" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
  • Here this code will be inside activity tag and this handles the ACTION_SEND intent for text/plain type i.e. whenever we will share any data that have type text/plain this will handle it.

  • If another application sent us an intent, we can handle it in our activity code by calling getIntent().

Intent receivedIntent = getIntent();
String sharedText = receivedIntent.getStringExtra(Intent.EXTRA_TEXT);
if(sharedText!=null){
		TextView debugText = findViewById(R.id.debug_text);
		debugText.setText("Shared: " + sharedText);
}

Last updated

Was this helpful?