您的位置:首页 > 移动开发 > Android开发

Settings: android 组件如何响应语言变化

2012-09-13 17:07 351 查看
原文:http://blog.csdn.net/androidbluetooth/article/details/7182541

这里所说的 android 组件,主要是指 android 中 Activity、Service、ContentProvider 以及 BroadcastReceiver.

在 android 源码开发的过程中,大家拿到手的都是一样的 android 源码,但是硬件平台却是大相径庭,所以会引发各种各样的问题,于是乎,android 开发越发精彩!

这篇博客主要是在研究 Settings 源码时所激发的,把自己的经验拿出来分享一番!

我在设置语言之后,发现有些地方的语言还是没有改变,这个时候想起了 onConfigurationChanged 方法,先来看看这个方法。

public interface ComponentCallbacks

这个接口包括两个方法,其中一个就是onConfigurationChanged 方法。

Activity、Service、ContentProvider 都实现了这个接口,所以在代码中,我们可以重写这个方法,便于回调处理。那麽,这个方法何时才会被回调呢?

abstract voidonConfigurationChanged(Configuration newConfig)

Called by the system when the device configuration changes while your component is running.

设备配置发生变化的时候,就会回调。你可能实在憋不住要问,设备配置指哪些?

android:configChanges=["mcc", "mnc", "locale",

"touchscreen", "keyboard", "keyboardHidden",

"navigation", "screenLayout", "fontScale", "uiMode",

"orientation", "screenSize", "smallestScreenSize"]

这里需要提醒一下,如果使用 Activity 配合 onConfigurationChanged 方法,需要在其 menifest.xml 中添加:

android:configChanges 属性。

所以,如果你有需要可以在上面的三大组件中重写该方法,做你自己的逻辑处理!

如果,在 Settings 里面改变语言之后,在我们其它的 App 中可以注册某个广播就可以接收到这种变化,就更好了!

恩,当然可以!

注册一个广播:

[java] view
plaincopyprint?

<span style="font-size:18px;"><span style="font-family:'Comic Sans MS';">IntentFilter filter = new IntentFilter();

filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);

registerReceiver(receiver, filter);</span></span>

接收广播:

[java] view
plaincopyprint?

<span style="font-size:18px;"><span style="font-family:'Comic Sans MS';">private BroadcastReceiver receiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

if("android.intent.action.CONFIGURATION_CHANGED".equals(action)) {

// to do

}

}

};</span></span>

别忘记在合适的位置取消注册:

unregisterReceiver(receiver);

这样做的话,要比直接重写onConfigurationChanged 方法,更加灵活,因为有些没有实现这个接口的android组件一大把,但是接收广播对于大多数组件来说还还是比较简单的!在以后的博客中,我和大家交流一下关于自定义的View如何接收广播!

关于 Intent.ACTION_CONFIGURATION_CHANGED,可以参考 sdk 文档。

有的人说,我现在只关心设备语言变化的那个 action,到底有木有?有!

Intent.ACTION_LOCALE_CHANGED
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: