ソースコード source code

下記アプリの主要なソースコードを公開しています。アプリ開発の参考になれば幸いです。

画像等が別途必要ですので下記情報のみでアプリが完成するものではありません。 アプリは少しずつ機能拡張していますのでストア公開されているアプリと内容が異なる場合があります。 コードはコピーして自由にお使いいただけます。ただし著作権は放棄しておりませんので全部の再掲載はご遠慮ください。部分的に再掲載したり、改変して再掲載するのは構いません。 自身のアプリ作成の参考として個人使用・商用問わず自由にお使いいただけます。 コード記述のお手本を示すものではありません。ミニアプリですので変数名などさほど気遣いしていない部分も有りますし間違いも有るかと思いますので参考程度にお考え下さい。 他の賢者の皆様が公開されているコードを参考にした箇所も含まれます。Androidアプリ開発の熟練者が書いたコードではありません。 エンジニア向け技術情報共有サービスではありませんので説明は省いています。ご了承ください。 GitHubなどへの公開は予定しておりません。

下記コードの最終ビルド日: 2021-05-08

build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.4.32"
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app/build.gradle

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "jp.aosystem.biorhythm"
        minSdkVersion 26
        targetSdkVersion 30
        multiDexEnabled true
        versionCode 17
        versionName "1.16"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        viewBinding true
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'com.google.android.gms:play-services-ads:20.1.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

app/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jp.aosystem.biorhythm">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Biorhythm">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SettingActivity" />
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-0000000000000000~0000000000">
        </meta-data>
    </application>

</manifest>

app/src/main/java/jp/aosystem/biorhythm/MainActivity.kt

package jp.aosystem.biorhythm

import android.app.Activity
import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.os.LocaleList
import android.util.DisplayMetrics
import android.view.View
import android.view.ViewGroup
import android.webkit.WebSettings
import android.widget.DatePicker
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.MobileAds
import jp.aosystem.biorhythm.databinding.ActivityMainBinding
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.util.*


class MainActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener {
    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: ConstraintLayout

    //adMob
    private lateinit var adView: AdView     //adMob
    private val adSize: AdSize
        get() {
            val display = windowManager.defaultDisplay
            val outMetrics = DisplayMetrics()
            display.getMetrics(outMetrics)
            val density = outMetrics.density
            var adWidthPixels = this.binding.adContainer.width.toFloat()
            if (adWidthPixels == 0f) {
                adWidthPixels = outMetrics.widthPixels.toFloat()
            }
            val adWidth = (adWidthPixels / density).toInt()
            return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth)
        }

    companion object {
        private const val AD_UNIT_ID: String = "ca-app-pub-0000000000000000/0000000000"     //adMob
        private const val RESULT_SETTING_ACTIVITY: Int = 1
        internal const val SETTINGS: String = "settings"
        internal const val THEME_NUMBER: String = "themeNumber"
        internal const val LOCALE_LANGUAGE: String = "localeLanguage"
        private const val DEFAULT_BIRTH: String = "2000/01/01"
    }

    private var themeNumber: Int = 0            //テーマ切り替え覚え
    private var localeLanguage: String = ""
    private var datePickerText: String = ""     //datePickerの呼び出し元を記録
    private var tabNumber: Int = 1           //タブの番号

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        this.binding = ActivityMainBinding.inflate(layoutInflater)
        this.viewModel = this.binding.root
        setContentView(this.viewModel)
        //タイトルバー非表示
        supportActionBar?.hide()
        //テーマ読み込みと設定
        this.loadThemeNumber()
        this.setTheme()
        //現在日付をセット
        val nowDate: LocalDate = LocalDate.now()
        val dtf: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd")
        this.binding.textToday.text = nowDate.format(dtf)
        //誕生日を読み出し
        this.initTabName()
        this.loadBirth()
        //adMob
        MobileAds.initialize(this) {}
        adView = AdView(this)
        this.binding.adContainer.addView(adView)
        loadBanner()
        //webViewの設定
        val webSettings: WebSettings = this.binding.webView.settings
        webSettings.javaScriptEnabled = true    //setJavaScriptEnabled を使用すると、アプリケーションに XSS の脆弱性が侵入する可能性があります。と表示されているだけ。
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        //webViewのサイズを自動設定
        this.binding.webView.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        //webViewのスクロールを抑制 (webViewのサイズを自動設定によって、不要になった)
        //this.webView.setOnTouchListener(OnTouchListener { v: View, event -> event.action == MotionEvent.ACTION_MOVE })
        //バイオリズム描画
        this.bioCalc()
    }

    //adMob
    private fun loadBanner() {
        adView.adUnitId = AD_UNIT_ID
        adView.adSize = adSize
        val adRequest = AdRequest
            .Builder()
            //.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build()
        adView.loadAd(adRequest)
    }

    //datePickerの戻り
    override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) {
        val str: String = String.format(
                Locale.JAPANESE,
                "%d/%02d/%02d",
                year,
                monthOfYear + 1,
                dayOfMonth
        )
        when (this.datePickerText) {
            "text_birth" -> {
                this.binding.textBirth.text = str
                saveBirth(str)
            }
            "text_today" -> {
                this.binding.textToday.text = str
            }
        }
        this.bioCalc()
    }

    //datePicker誕生日
    fun birthDatePicker(v: View) {
        this.datePickerText = "text_birth"
        val dt: String = this.binding.textBirth.text.toString() + "//"
        val dtAry: List<String> = dt.split("/")
        val args: Bundle = Bundle()     //Fragment側に渡す変数
        args.putString("text0", dtAry[0])
        args.putString("text1", dtAry[1])
        args.putString("text2", dtAry[2])
        val newFragment: DatePickerDialogFragment = DatePickerDialogFragment()
        newFragment.arguments = args
        newFragment.show(supportFragmentManager, "datePicker")
    }

    //datePicker表示日
    fun todayDatePicker(v: View) {
        this.datePickerText = "text_today"
        val dt: String = this.binding.textToday.text.toString() + "//"
        val dtAry: List<String> = dt.split("/")
        val args: Bundle = Bundle()     //Fragment側に渡す変数
        args.putString("text0", dtAry[0])
        args.putString("text1", dtAry[1])
        args.putString("text2", dtAry[2])
        val newFragment: DatePickerDialogFragment = DatePickerDialogFragment()
        newFragment.arguments = args
        newFragment.show(supportFragmentManager, "datePicker")
    }

    //バイオリズム描画(基本計算)
    private fun bioCalc() {
        val dtf: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd")
        val birth: LocalDate = LocalDate.parse(this.binding.textBirth.text.toString(), dtf)
        val today: LocalDate = LocalDate.parse(this.binding.textToday.text.toString(), dtf)
        val diff: Long = ChronoUnit.DAYS.between(birth, today)
        val bioP: Int = (diff % 23).toInt()
        val bioS: Int = (diff % 28).toInt()
        val bioI: Int = (diff % 33).toInt()
        this.drawHTML(today, bioP, bioS, bioI);
    }

    //バイオリズム描画SVG
    private fun drawHTML(today: LocalDate, bioP: Int, bioS: Int, bioI: Int) {
        val biorhythmGreen: String = this.toRGB(ContextCompat.getColor(this, R.color.biorhythmGreen))
        val biorhythmRed: String = this.toRGB(ContextCompat.getColor(this, R.color.biorhythmRed))
        val biorhythmBlue: String = this.toRGB(ContextCompat.getColor(this, R.color.biorhythmBlue))
        val biorhythmBG: String = this.toRGB(ContextCompat.getColor(this, R.color.biorhythmBG))
        val biorhythmFill1: String = this.toRGB(ContextCompat.getColor(this, R.color.biorhythmFill1))
        val biorhythmStroke1: String = this.toRGB(ContextCompat.getColor(this, R.color.biorhythmStroke1))
        val biorhythmStroke2: String = this.toRGB(ContextCompat.getColor(this, R.color.biorhythmStroke2))
        val biorhythmStroke3: String = this.toRGB(ContextCompat.getColor(this, R.color.biorhythmStroke3))
        val biorhythmStroke4: String = this.toRGB(ContextCompat.getColor(this, R.color.biorhythmStroke4))

        val prefix1: String = "<!doctype html><html><head>"
        val prefix2: String = "</head><body>"
        var style: String = "<style>"
        style += "html{background-color:${biorhythmBG};}"
        style += "body{margin:0 10px;user-select:none;}"
        style += ".svgTxt1{fill:${biorhythmFill1};font-size:11px;font-family:sans-serif;}"
        style += ".svgSt00{fill:none;stroke:${biorhythmStroke1};}"     //000 stroke1
        style += ".svgSt0{fill:none;stroke:${biorhythmStroke2};}"      //888 stroke2
        style += ".svgSt1{fill:none;stroke:${biorhythmStroke4};}"      //ddd stroke4
        style += ".svgSt2{fill:none;stroke:${biorhythmStroke3};}"      //ccc stroke3
        style += ".svgSt3{fill:none;stroke:${biorhythmStroke3};stroke-dasharray:2,2;}"     //ccc stroke3
        style += "#svgSt4{fill:none;stroke:${biorhythmGreen};}"
        style += "#svgSt5{fill:none;stroke:${biorhythmRed};}"
        style += "#svgSt6{fill:none;stroke:${biorhythmBlue};}"
        style += "</style>"
        val postfix: String = "</body></html>"
        var svgStr: String = ""
        svgStr += "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\" viewBox=\"0 0 400 200\" style=\"enable-background:new 0 0 400 200;\" xml:space=\"preserve\">"
        svgStr += "<line class=\"svgSt1\" x1=\"399.5\" y1=\"15\" x2=\"399.5\" y2=\"175\"/>"
        svgStr += "<line class=\"svgSt2\" x1=\"0\" y1=\"15.5\" x2=\"400\" y2=\"15.5\"/>"
        svgStr += "<line class=\"svgSt3\" x1=\"0\" y1=\"55.5\" x2=\"400\" y2=\"55.5\"/>"
        svgStr += "<line class=\"svgSt2\" x1=\"0\" y1=\"95.5\" x2=\"400\" y2=\"95.5\"/>"
        svgStr += "<line class=\"svgSt3\" x1=\"0\" y1=\"135.5\" x2=\"400\" y2=\"135.5\"/>"
        svgStr += "<line class=\"svgSt2\" x1=\"0\" y1=\"173.5\" x2=\"400\" y2=\"173.5\"/>"
        var x: Float = 0F
        for (i: Int in 0..39) {
            x = (i * 10 + 0.5).toFloat()
            if (((i + 1) % 4) == 0) {
                if (i == 3) {
                    svgStr += "<line class=\"svgSt00\" x1=\"${x}\" y1=\"15\" x2=\"${x}\" y2=\"181\"/>"
                } else {
                    svgStr += "<line class=\"svgSt0\" x1=\"${x}\" y1=\"16\" x2=\"${x}\" y2=\"181\"/>"
                }
            } else {
                svgStr += "<line class=\"svgSt1\" x1=\"${x}\" y1=\"16\" x2=\"${x}\" y2=\"173\"/>"
            }
        }
        svgStr += "<path id=\"svgSt4\" transform=\"matrix(1 0 0 1 ${bioP * -10} -5.5)\" d=\"M-199.5,99.5c9.2-23.9,31-79,57-79s48.8,55.1,58,79s31,79,57,79s48.8-55.1,58-79s31-79,57-79s48.8,55.1,58,79s31,79,57,79s48.8-55.1,58-79s31-79,57-79s48.8,55.1,58,79s31,79,57,79s48.8-55.1,58-79s31-79,57-79s48.8,55.1,58,79s31,79,57,79s48.8-55.1,58-79\"/>"
        svgStr += "<path id=\"svgSt5\" transform=\"matrix(1 0 0 1 ${bioS * -10} -5.5)\" d=\"M-249.5,99.5c10.6-23.2,40-79,70-79s59.4,55.8,70,79s40,79,70,79s59.4-55.8,70-79s40-79,70-79s59.4,55.8,70,79s40,79,70,79s59.4-55.8,70-79s40-79,70-79s59.4,55.8,70,79s40,79,70,79s59.4-55.8,70-79s40-79,70-79s59.4,55.8,70,79s40,79,70,79s59.4-55.8,70-79\"/>"
        svgStr += "<path id=\"svgSt6\" transform=\"matrix(1 0 0 1 ${bioI * -10} -5.5)\" d=\"M-299.5,99.5c13-23,44-79,83-79s69,56,82,79s44,79,83,79s69-56,82-79s44-79,83-79s69,56,82,79s44,79,83,79s69-56,82-79s44-79,83-79s69,56,82,79s44,79,83,79s69-56,82-79s44-79,83-79s69,56,82,79s44,79,83,79s69-56,82-79\"/>"
        var currentDay: LocalDate = today
        for (i: Int in 0..39) {
            if (i % 4 == 0) {
                var x1: Int = i * 10 + 21
                if (currentDay.monthValue >= 10) {
                    x1 -= 6
                }
                svgStr += "<text class=\"svgTxt1\" transform=\"matrix(1 0 0 1 ${x1} 193)\">${currentDay.monthValue}/${currentDay.dayOfMonth}</text>"
                currentDay = currentDay.plusDays(4)
            }
        }
        svgStr += "</svg>"
        //this.webView.clearCache(true)
        //this.webView.loadData(prefix1 + style + prefix2 + svgStr + postfix, "text/html", "utf-8")     //ダメ
        this.binding.webView.loadDataWithBaseURL(null, prefix1 + style + prefix2 + svgStr + postfix, "text/html", "utf-8", null)
        //this.webView.reload()     //これを入れるとリフレッシュされない
    }

    // ウェブ用カラーに変換 0xFF0000 to "rgb(255,0,0)"
    private fun toRGB(hex: Int): String {
        val r = hex and 0xFF0000 shr 16
        val g = hex and 0xFF00 shr 8
        val b = hex and 0xFF
        return "rgb(${r},${g},${b})"
    }

    //--------------------------------------------------------------------------------

    fun onClickTab1(v: View) {
        this.tabNumber = 1
        this.loadBirth()
        this.bioCalc()
    }

    fun onClickTab2(v: View) {
        this.tabNumber = 2
        this.loadBirth()
        this.bioCalc()
    }

    fun onClickTab3(v: View) {
        this.tabNumber = 3
        this.loadBirth()
        this.bioCalc()
    }

    fun onClickTab4(v: View) {
        this.tabNumber = 4
        this.loadBirth()
        this.bioCalc()
    }

    fun onClickTab5(v: View) {
        this.tabNumber = 5
        this.loadBirth()
        this.bioCalc()
    }

    fun onClickSetting(v: View) {
        val intent = Intent(applicationContext, SettingActivity::class.java)
        intent.putExtra(THEME_NUMBER, this.themeNumber)
        intent.putExtra(LOCALE_LANGUAGE, this.localeLanguage)
        startActivityForResult(intent, RESULT_SETTING_ACTIVITY)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        super.onActivityResult(requestCode, resultCode, intent)
        if (resultCode == Activity.RESULT_OK && requestCode == RESULT_SETTING_ACTIVITY && intent != null) {
            var reCreateFlag: Boolean = false
            val lastThemeNumber: Int = this.themeNumber
            this.themeNumber = intent.getIntExtra(THEME_NUMBER, 0)
            if (this.themeNumber != lastThemeNumber) {
                this.saveThemeNumber()
                reCreateFlag = true
            }
            val lastLocaleLanguage = this.localeLanguage
            this.localeLanguage = intent.getStringExtra(LOCALE_LANGUAGE) ?: ""
            if (this.localeLanguage != lastLocaleLanguage) {
                this.saveLocaleLanguage()
                reCreateFlag = true
            }
            if (reCreateFlag) {
                recreate()
            }
        }
    }

    //--------------------------------------------------------------------------------

    //誕生日を保存
    private fun saveBirth(str: String) {
        getSharedPreferences(SETTINGS, Context.MODE_PRIVATE).edit().apply {
            when (this@MainActivity.tabNumber) {
                1 -> {
                    putString("birthDate1", str)
                    this@MainActivity.binding.textTab1.text = str
                }
                2 -> {
                    putString("birthDate2", str)
                    this@MainActivity.binding.textTab2.text = str
                }
                3 -> {
                    putString("birthDate3", str)
                    this@MainActivity.binding.textTab3.text = str
                }
                4 -> {
                    putString("birthDate4", str)
                    this@MainActivity.binding.textTab4.text = str
                }
                5 -> {
                    putString("birthDate5", str)
                    this@MainActivity.binding.textTab5.text = str
                }
            }
            apply()
        }
    }

    //誕生日を読み出し
    private fun loadBirth() {
        this.binding.textTab1.setTextColor(Color.BLACK)
        this.binding.textTab2.setTextColor(Color.BLACK)
        this.binding.textTab3.setTextColor(Color.BLACK)
        this.binding.textTab4.setTextColor(Color.BLACK)
        this.binding.textTab5.setTextColor(Color.BLACK)
        //
        val pref = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE)
        var birthDate: String = DEFAULT_BIRTH
        when (this.tabNumber) {
            1 -> {
                birthDate = pref.getString("birthDate1", DEFAULT_BIRTH).toString()
                this.binding.textTab1.setTextColor(Color.YELLOW)
            }
            2 -> {
                birthDate = pref.getString("birthDate2", DEFAULT_BIRTH).toString()
                this.binding.textTab2.setTextColor(Color.YELLOW)
            }
            3 -> {
                birthDate = pref.getString("birthDate3", DEFAULT_BIRTH).toString()
                this.binding.textTab3.setTextColor(Color.YELLOW)
            }
            4 -> {
                birthDate = pref.getString("birthDate4", DEFAULT_BIRTH).toString()
                this.binding.textTab4.setTextColor(Color.YELLOW)
            }
            5 -> {
                birthDate = pref.getString("birthDate5", DEFAULT_BIRTH).toString()
                this.binding.textTab5.setTextColor(Color.YELLOW)
            }
        }
        this.binding.textBirth.text = birthDate         //生年月日変更
    }

    //誕生日の初期値を設定
    private fun initTabName() {
        val pref = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE)
        this.binding.textTab1.text = pref.getString("birthDate1", DEFAULT_BIRTH).toString()
        this.binding.textTab2.text = pref.getString("birthDate2", DEFAULT_BIRTH).toString()
        this.binding.textTab3.text = pref.getString("birthDate3", DEFAULT_BIRTH).toString()
        this.binding.textTab4.text = pref.getString("birthDate4", DEFAULT_BIRTH).toString()
        this.binding.textTab5.text = pref.getString("birthDate5", DEFAULT_BIRTH).toString()
    }

    //--------------------------------------------------------------------------------

    //テーマを保存
    private fun saveThemeNumber() {
        getSharedPreferences(SETTINGS, Context.MODE_PRIVATE).edit().apply {
            putInt(THEME_NUMBER, this@MainActivity.themeNumber)
            apply()
        }
    }

    //テーマを読み出し
    private fun loadThemeNumber() {
        val pref = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE)
        this.themeNumber = pref.getInt(THEME_NUMBER, 0)
    }

    //テーマを設定
    private fun setTheme() {
        when (this.themeNumber) {
            0 -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            1 -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
        }
    }

    //--------------------------------------------------------------------------------

    //localeLanguageを保存
    private fun saveLocaleLanguage() {
        getSharedPreferences(SETTINGS, Context.MODE_PRIVATE).edit().apply {
            putString(LOCALE_LANGUAGE, this@MainActivity.localeLanguage)
            apply()
        }
    }

    //言語設定
    override fun attachBaseContext(base: Context) {
        val pref = base.getSharedPreferences(SETTINGS, Context.MODE_PRIVATE)
        this.localeLanguage = pref.getString(LOCALE_LANGUAGE, "") ?: ""
        val loc: Locale? = if (this.localeLanguage != "") Locale(this.localeLanguage) else null
        if (loc != null) {
            val res = base.resources
            val config = Configuration(res.configuration)
            val localeList = LocaleList(loc)
            LocaleList.setDefault(localeList)
            config.setLocales(localeList)
            super.attachBaseContext(base.createConfigurationContext(config))
        } else {
            super.attachBaseContext(base)
        }
    }

    //--------------------------------------------------------------------------------

}

app/src/main/java/jp/aosystem/biorhythm/SettingActivity.kt

package jp.aosystem.biorhythm

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.os.LocaleList
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import jp.aosystem.biorhythm.databinding.ActivitySettingBinding
import java.util.*

class SettingActivity : AppCompatActivity() {
    private lateinit var binding: ActivitySettingBinding
    private lateinit var viewModel: ConstraintLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        this.binding = ActivitySettingBinding.inflate(layoutInflater)
        this.viewModel = this.binding.root
        setContentView(this.viewModel)
        //データ受け取り
        val intent = this.intent
        val themeNumber: Int = intent.getIntExtra(MainActivity.THEME_NUMBER,0)
        this.binding.switchTheme.isChecked = themeNumber != 0
        val localeLanguage: String = intent.getStringExtra(MainActivity.LOCALE_LANGUAGE) ?: ""
        when (localeLanguage) {
            "en" -> this.binding.radioLanguageEn.isChecked = true
            "ja" -> this.binding.radioLanguageJa.isChecked = true
            else -> this.binding.radioLanguageSystem.isChecked = true
        }
        //タイトルバー非表示
        supportActionBar?.hide()
    }

    fun onClickApply(v: View) {
        val themeNumber = if (this.binding.switchTheme.isChecked) 1 else 0
        var localeLanguage: String = ""
        if (this.binding.radioLanguageEn.isChecked) {
            localeLanguage = "en"
        } else if (this.binding.radioLanguageJa.isChecked) {
            localeLanguage = "ja"
        }
        val intent = Intent()
        intent.putExtra(MainActivity.THEME_NUMBER, themeNumber)
        intent.putExtra(MainActivity.LOCALE_LANGUAGE, localeLanguage)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    fun onClickCancel(v: View) {
        val intent = Intent()
        setResult(Activity.RESULT_CANCELED, intent)
        finish()
    }

    //--------------------------------------------------------------------------------

    //言語設定
    override fun attachBaseContext(base: Context) {
        val pref = base.getSharedPreferences(MainActivity.SETTINGS, Context.MODE_PRIVATE)
        val localeLanguage: String = pref.getString(MainActivity.LOCALE_LANGUAGE, "") ?: ""
        val loc: Locale? = if (localeLanguage != "") Locale(localeLanguage) else null
        if (loc != null) {
            val res = base.resources
            val config = Configuration(res.configuration)
            val localeList = LocaleList(loc)
            LocaleList.setDefault(localeList)
            config.setLocales(localeList)
            super.attachBaseContext(base.createConfigurationContext(config))
        } else {
            super.attachBaseContext(base)
        }
    }

    //--------------------------------------------------------------------------------

}

app/src/main/java/jp/aosystem/biorhythm/DatePickerDialogFragment.kt

package jp.aosystem.biorhythm

import android.app.DatePickerDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import java.util.*

class DatePickerDialogFragment : DialogFragment(), DatePickerDialog.OnDateSetListener {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        //Activityから受け取る変数
        var year: Int = arguments!!.getString("text0")!!.toIntOrNull() ?: 0
        var month: Int = arguments!!.getString("text1")!!.toIntOrNull() ?: 0
        var day: Int = arguments!!.getString("text2")!!.toIntOrNull() ?: 0
        month -= 1  //1-12 to 0-11
        if (year == 0) {
            val c = Calendar.getInstance()
            year = c.get(Calendar.YEAR)
            month = c.get(Calendar.MONTH)
            day = c.get(Calendar.DAY_OF_MONTH)
        }
        return DatePickerDialog(
            this.context as Context, activity as MainActivity?, year, month, day)
    }

    override fun onDateSet(view: android.widget.DatePicker, year: Int,
                           monthOfYear: Int, dayOfMonth: Int) {
    }

}

app/src/main/res/layout/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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/textTitle"
                        android:layout_width="wrap_content"
                        android:layout_height="48dp"
                        android:layout_weight="6"
                        android:background="@color/title"
                        android:gravity="center"
                        android:text="@string/title" />

                    <TextView
                        android:id="@+id/textSetting"
                        android:layout_width="wrap_content"
                        android:layout_height="48dp"
                        android:layout_weight="1"
                        android:background="@color/setting"
                        android:gravity="center"
                        android:onClick="onClickSetting"
                        android:text="@string/setting" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/textTab1"
                        android:layout_width="wrap_content"
                        android:layout_height="48dp"
                        android:layout_weight="1"
                        android:background="@color/tab1"
                        android:gravity="center"
                        android:onClick="onClickTab1"
                        android:text="@string/birthInit"
                        android:textSize="12sp" />

                    <TextView
                        android:id="@+id/textTab2"
                        android:layout_width="wrap_content"
                        android:layout_height="48dp"
                        android:layout_weight="1"
                        android:background="@color/tab2"
                        android:gravity="center"
                        android:onClick="onClickTab2"
                        android:text="@string/birthInit"
                        android:textSize="12sp" />

                    <TextView
                        android:id="@+id/textTab3"
                        android:layout_width="wrap_content"
                        android:layout_height="48dp"
                        android:layout_weight="1"
                        android:background="@color/tab3"
                        android:gravity="center"
                        android:onClick="onClickTab3"
                        android:text="@string/birthInit"
                        android:textSize="12sp" />

                    <TextView
                        android:id="@+id/textTab4"
                        android:layout_width="wrap_content"
                        android:layout_height="48dp"
                        android:layout_weight="1"
                        android:background="@color/tab4"
                        android:gravity="center"
                        android:onClick="onClickTab4"
                        android:text="@string/birthInit"
                        android:textSize="12sp" />

                    <TextView
                        android:id="@+id/textTab5"
                        android:layout_width="wrap_content"
                        android:layout_height="48dp"
                        android:layout_weight="1"
                        android:background="@color/tab5"
                        android:gravity="center"
                        android:onClick="onClickTab5"
                        android:text="@string/birthInit"
                        android:textSize="12sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="12dp"
                    android:gravity="center"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <TextView
                            android:id="@+id/textView1"
                            android:layout_width="50dp"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:paddingTop="15dp"
                            android:text="@string/birth" />

                        <TextView
                            android:id="@+id/text_birth"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:clickable="true"
                            android:onClick="birthDatePicker"
                            android:text="@string/birthInit"
                            android:textSize="40sp"
                            tools:ignore="OnClick" />
                    </LinearLayout>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="5dp"
                    android:gravity="center"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <TextView
                            android:id="@+id/textView2"
                            android:layout_width="50dp"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:paddingTop="15dp"
                            android:text="@string/today" />

                        <TextView
                            android:id="@+id/text_today"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:clickable="true"
                            android:onClick="todayDatePicker"
                            android:text="@string/todayInit"
                            android:textSize="40sp"
                            tools:ignore="OnClick" />
                    </LinearLayout>

                </LinearLayout>

                <WebView
                    android:id="@+id/webView"
                    android:layout_width="match_parent"
                    android:layout_height="180dp"
                    android:layout_marginTop="20dp" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="0"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/textView7"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:gravity="center"
                        android:text="@string/physical"
                        android:textColor="@color/biorhythmGreen" />

                    <TextView
                        android:id="@+id/textView8"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="@string/sensitivity"
                        android:textColor="@color/biorhythmRed" />

                    <TextView
                        android:id="@+id/textView9"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="@string/intellectual"
                        android:textColor="@color/biorhythmBlue" />
                </LinearLayout>


                <Space
                    android:layout_width="match_parent"
                    android:layout_height="130dp"
                    android:layout_weight="0" />

            </LinearLayout>
        </ScrollView>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/ad_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent">

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

app/src/main/res/layout/activity_setting.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SettingActivity">
    <LinearLayout
        android:id="@+id/layoutButtons"
        android:layout_width="match_parent"
        android:layout_height="48dip"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textCancel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="6"
            android:background="@color/cancel"
            android:gravity="center"
            android:minHeight="48dip"
            android:onClick="onClickCancel"
            android:text="@string/cancel" />

        <TextView
            android:id="@+id/textVerification"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="6"
            android:background="@color/apply"
            android:gravity="center"
            android:minHeight="48dip"
            android:onClick="onClickApply"
            android:text="@string/apply" />

    </LinearLayout>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/layoutButtons">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:orientation="vertical"
            android:paddingLeft="20dp"
            android:paddingTop="20dp"
            android:paddingRight="20dp"
            android:paddingBottom="50dp">

            <androidx.appcompat.widget.SwitchCompat
                android:id="@+id/switchTheme"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/darkTheme" />

            <View
                android:id="@+id/divider3"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginTop="10dp"
                android:background="?android:attr/listDivider" />

            <TextView
                android:id="@+id/textLanguage"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:text="@string/language"
                android:textColor="?android:attr/textColorPrimary" />

            <RadioGroup
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
                <RadioButton
                    android:id="@+id/radioLanguageSystem"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/languageSystem" />
                <RadioButton
                    android:id="@+id/radioLanguageEn"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/languageEn" />
                <RadioButton
                    android:id="@+id/radioLanguageJa"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/languageJa" />

            </RadioGroup>

            <View
                android:id="@+id/divider"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginTop="20dp"
                android:background="?android:attr/listDivider" />

            <TextView
                android:id="@+id/textUsage1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:text="@string/usage1"
                android:textSize="12sp" />

            <View
                android:id="@+id/divider2"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginTop="20dp"
                android:background="?android:attr/listDivider" />

            <TextView
                android:id="@+id/textUsage2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:text="@string/usage2"
                android:textSize="12sp" />

            <ImageView
                android:id="@+id/imageUsage1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:adjustViewBounds="true"
                app:srcCompat="@drawable/ic_usage1" />

            <ImageView
                android:id="@+id/imageUsage2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:adjustViewBounds="true"
                app:srcCompat="@drawable/ic_usage2" />

            <Space
                android:layout_width="match_parent"
                android:layout_height="150dp" />
        </LinearLayout>
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>