[Java] I want to go back to the previous screen with kotlin and java!

1 minute read

Introduction…

This article was written in 5 previous articles,

** 6th day of posting articles every day for 7 days **

Has become

The code to use is attached below, but please see the article 5 before that for detailed functions of this application!

  • java version: https://github.com/sato-na/guruwake_java

  • kotlin version: https://github.com/sato-na/guruwake_kotlin

↓ Here is the main subject of this article ↓

To return to the previous screen in each language…

*This is the method to return to the previous screen from the back button on the toolbar.

Toolbar implementation

  • for java
Toolbar variable name = findViewById(R.id. toolbar id);
setSupportActionBar (variable);

Example)

WhoActiity.java


Toolbar whoTb = findViewById(R.id.who_tb); // line 30
setSupportActionBar(whoTb);
  • For kotlin
setSupportActionBar (toolbar id)

Example)

WhoActivity.kt


setSupportActionBar(who_tb) // line 21

java needs to create a ToolBar type variable, kotlin does not

How to return by adding a return button to the toolbar

  • for java

(in the onCreate function)

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

(outside the onCreate function)

@Override
public boolean onSupportNavigateUp() {
    finish();
    return super.onSupportNavigateUp();
}

Example) (in the onCreate function)

WhoActivity.java


getSupportActionBar().setDisplayShowHomeEnabled(true); // line 32
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

(outside the onCreate function)

WhoActivity.java


@Override // Line 69
public boolean onSupportNavigateUp() {
    finish();
    return super.onSupportNavigateUp();
}
  • For kotlin
supportActionBar?.let {// line 22
    it.setDisplayHomeAsUpEnabled(true)
    it.setHomeButtonEnabled(true)
} ?: IllegalAccessException("Toolbar cannot be null")

AndroidManifest.xml


<activity
    android:name=".WhoActivity"
    android:parentActivityName=".MainActivity" /> // Add here

Example)

WhoActivity.kt


supportActionBar?.let {// line 22
    it.setDisplayHomeAsUpEnabled(true)
    it.setHomeButtonEnabled(true)
} ?: IllegalAccessException("Toolbar cannot be null")

AndroidManifest.xml


<activity // line 20
    android:name=".WhoActivity"
    android:parentActivityName=".MainActivity" />

java needs to define code and new function, kotlin needs to edit code and AndroidManifest.xml

Finally…

This time I went back to the previous screen using the toolbar with java and kotlin. I felt that both languages needed more complicated code than screen transitions.

I’ll be posting an article tomorrow, so stay warm and watch.