app/src/main/java/jp/aosystem/htmlentitynumber/MainActivity.kt
package jp.aosystem.htmlentitynumber
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.LocaleList
import android.text.Editable
import android.text.TextWatcher
import android.util.DisplayMetrics
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.app.AppCompatDelegate.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.text.HtmlCompat
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.htmlentitynumber.databinding.ActivityMainBinding
import java.util.*
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var viewModel: ConstraintLayout
private var inputMethodManager: InputMethodManager? = null
private var themeNumber: Int = 0 //0 or 1
private var localeLanguage: String = ""
//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 = "ca-app-pub-3940256099942544/6300978111" //adMob Test
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"
}
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()
//adMob
MobileAds.initialize(this) {}
this.adView = AdView(this)
this.binding.adContainer.addView(this.adView)
this.loadBanner()
//
this.setTouchListener()
this.setTextChangeListener()
}
//adMob
private fun loadBanner() {
this.adView.adUnitId = AD_UNIT_ID
this.adView.adSize = adSize
val adRequest = AdRequest
.Builder()
//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build()
this.adView.loadAd(adRequest)
}
//背景タッチでテキストエリアからフォーカスを外してキーボードを隠す
private fun setTouchListener() {
this.inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
this.binding.editPlain.setOnFocusChangeListener { _, hasFocus ->
if (!hasFocus) {
this.inputMethodManager!!.hideSoftInputFromWindow( //キーボードを隠す
this.binding.editPlain.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS
)
// 背景にフォーカスを移す
//this.binding.textTitle.requestFocus()
}
}
this.binding.editEntity.setOnFocusChangeListener { _, hasFocus ->
if (!hasFocus) {
this.inputMethodManager!!.hideSoftInputFromWindow( //キーボードを隠す
this.binding.editEntity.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS
)
// 背景にフォーカスを移す
//this.binding.textTitle.requestFocus()
}
}
this.binding.editDecode.setOnFocusChangeListener { _, hasFocus ->
if (!hasFocus) {
this.inputMethodManager!!.hideSoftInputFromWindow( //キーボードを隠す
this.binding.editDecode.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS
)
// 背景にフォーカスを移す
//this.binding.textTitle.requestFocus()
}
}
}
private fun setTextChangeListener() {
this.binding.editPlain.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
this@MainActivity.calcPlane()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
this.binding.editEntity.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
this@MainActivity.calcEntity()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
}
private fun calcPlane() {
val valPlane: String = this.binding.editPlain.text.toString()
var str: String = ""
valPlane.forEach {
val c: String = it.toInt().toString(16)
str += "${c};"
}
this.binding.editEntity.setText(str)
this.calcEntity()
}
private fun calcEntity() {
val valEntity: String = this.binding.editEntity.text.toString()
val decodeStr = HtmlCompat.fromHtml(valEntity, HtmlCompat.FROM_HTML_MODE_LEGACY)
this.binding.editDecode.setText(decodeStr)
}
//--------------------------------------------------------------------------------
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 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)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //minSdkVersion 24
val localeList = LocaleList(loc)
LocaleList.setDefault(localeList)
config.setLocales(localeList)
} else { //minSdkVersion 17 16はダメ
config.setLocale(loc)
}
super.attachBaseContext(base.createConfigurationContext(config))
} else {
super.attachBaseContext(base)
}
}
//----------------------------------------------
}
app/src/main/java/jp/aosystem/htmlentitynumber/SettingActivity.kt
package jp.aosystem.htmlentitynumber
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
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.htmlentitynumber.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)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //minSdkVersion 24
val localeList = LocaleList(loc)
LocaleList.setDefault(localeList)
config.setLocales(localeList)
} else { //minSdkVersion 17 16はダメ
config.setLocale(loc)
}
super.attachBaseContext(base.createConfigurationContext(config))
} else {
super.attachBaseContext(base)
}
}
//--------------------------------------------------
}