Basic overview of Android App
Sun, 03 Nov 2024
import java.util.Scanner;
public class Bit2Byte {
static class Calculator{
private Adder adder;
// assume other code here
public void setAdder(Adder adder) {
this.adder = adder;
}
public void printSum(int a, int b){
if(adder == null) return;
System.out.println("Sum is: "+adder.add(a,b));
}
static class Adder{
public int add(int numOne, int numTwo){
return numOne + numTwo;
}
}
}
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
final int a = scanner.nextInt();
final int b = scanner.nextInt();
// assume a = 2, b = 4
final Calculator calculator = new Calculator(); // <-------------------- (1)
calculator.printSum(a, b);
calculator.setAdder(new Calculator.Adder());
calculator.printSum(a, b);
}
}
main()
method as expected.1
) gets executed immediately?.java
file. Anything else?XML
file and a Java
file, and a way to connect them.MainActivity.java
and XML part named activity_main.xml
.java
file runs in terminal,xml
isn't so easy for us,main()
method, but we can't directly access it. It is handled by Android Framework.onCreate()
method to notify us.onCreate
can be considered as our visible entry point.activity_main.xml
)<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
)package com.lazymind.myfirstapp;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
setContentView()
, but haven't declared anywhere.AppCompatActivity
or any of its parent.setContentView
takes the name of our xml(R.layout.activity_main
) file, that we want to connect with. It then renders the files into UI.R.layout.activity_main
R
: resources(res
folder).layout
: folder.activity_main
: name of the file.AppCompatActivity
contains many many functions that we can use according to our need for maintaing lifecycle or connecting.java
.This is a comment 1.
This is a comment 2.