簡體   English   中英

檢測應用程序語言而不是手機語言

[英]Detect application language instead of phone language

我有多語言應用程序,如果應用程序翻譯不支持手機上的所選語言,我想用英語顯示日期。

是否有任何方法可以讓應用程序使用語言(默認英語)而不是手機中選擇的語言?

看起來這只返回手機語言:

Locale.getDefault()
getContext().getResources().getConfiguration().locale

截圖: 在此輸入圖像描述

獲取系統語言

Resources.getSystem().getConfiguration().locale.getLanguage();

獲取應用語言

String appLang = Locale.getDefault().getLanguage();

嘗試這個:

我已經制作了一個擴展函數來使用應用程序的默認語言環境或僅使用英語來格式化日期。

注意:此功能將始終以英語返回格式化日期,無論您的設備語言是什么或您的應用語言是什么都無關緊要。

如果您希望按照應用語言約會,只需將應用的所選語言區域設置傳遞給此方法即可。

顯示之前DatePickerDialog設置Localeen這樣。

Locale.setDefault(Locale("en"))
startDatePickerDialog.show()

然后使用此方法格式化日期。

 fun Context.getFormattedDate(
    inputFormat: String = "dd/MM/yyyy",
    outputFormat: String,
    inputDate: String,
    locale: Locale = Locale("en")
): String {

    val inputFormat = inputFormat
    var outputFormat = outputFormat

    var parsed: Date? = null
    var outputDate = ""

    val dfInput = SimpleDateFormat(inputFormat, locale)
    val dfOutput = SimpleDateFormat(outputFormat, locale)

    try {
        parsed = dfInput.parse(inputDate)
        outputDate = dfOutput.format(parsed)
    } catch (e: Exception) {
        Log.e("formattedDateFromString", "Exception in formate Date From string(): " + e.message)
        e.printStackTrace()
    }
    return outputDate

}

如何使用此功能

 Log.e("Formated date", getFormattedDate(
                    inputFormat = "dd/MM/yyyy",
                    outputFormat = "dd-MMM-yyyy",
                    inputDate = "17/05/2019"
                )
            )

由於沒有有用的答案,我將發布我的解決方案來解決這個問題。

所以我決定使用里面的語言環境代碼為每種支持的語言創建xml文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="language_locale">en</string>
</resources>

用法示例:

fun Date.formatWithShortMonthAndDay(context: Context, date: Date): String {
    val locale = context.resources.getString(R.string.language_locale)
    return SimpleDateFormat(DATE_WITH_SHORT_MONTH_AND_DAY_PATTERN, Locale(locale)).format(date)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM