Skip to content

自定义切换语言后刷新界面的方式

Reborn edited this page Dec 11, 2019 · 2 revisions

首先,下面是几个初始化刷新界面方式的常量:

LocaleConstant.RESTART_TO_LAUNCHER_ACTIVITY -> 重启到主页(非重启 AppLocaleConstant.RECREATE_CURRENT_ACTIVITY -> 重启已经打开的 Activity
LocaleConstant.CUSTOM_WAY_TO_UPDATE_INTERFACE -> 自己实现刷新界面的方式

插件默认初始化为LocaleConstant.RECREATE_CURRENT_ACTIVITY,若要自己实现,需要使用前先在Application初始化插件:

LocalePlugin.init(this, LocaleConstant.CUSTOM_WAY_TO_UPDATE_INTERFACE)

初始化过后,在切换语言的界面实现ActivityHelper.OnUpdateInterfaceListener接口、设置监听器,然后在接口方法体内写自己想要实现的刷新界面逻辑,如:

class SettingActivity : AppCompatActivity(), ActivityHelper.OnUpdateInterfaceListener {

    @SuppressLint("StringFormatInvalid")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)
        ...
        // 设置监听器
        ActivityHelper.getInstance().setOnUpdateInterfaceListener(this)
    }

    override fun updateInterface(context: Context, intent: Intent?) {
        // TODO: To write your way to update interface
        Toast.makeText(context, intent?.getStringExtra("Test"), Toast.LENGTH_LONG).show()
    }
}

然后在切换语言的时候调用:

// 应用切换的语言
LocaleHelper.getInstance()
    .language(which.toString())
    .apply(this@SettingActivity, intent, ActivityUtil)

举例:

val intent = Intent(this, MainActivity::class.java)
intent.putExtra("Test", getString(R.string.activity_custom_refresh_way_test))
LocaleHelper.getInstance()
    .language(which.toString())
    .apply(this@SettingActivity, intent, ActivityUtil)
You can’t perform that action at this time.