命名约定通过Android的额外传递数据 [英] naming convention for passing data through extras in android
问题描述
路过群众演员时,如Intent.putExtra(MYNAME,MYNAME),什么是对多余的名称约定?
when passing extras such as Intent.putExtra("myName", myName), what's the convention for the name of the extra?
例如:如果两个活动之间传递数据,既会放/提取数据的IDMYNAME下,但我应该只是硬codeMYNAME无处不在,或保留价值的R.values.string ?
ie: if passing data between two activities, both would put/extract data under the id "myName", but should I just hardcode "myName" everywhere, or keep the value in the R.values.string?
推荐答案
硬编码绝对不是一个理想的解决方案。
Hardcoding is definitely not an ideal solution.
在Android框架中使用的约定是创建一个名为公共静态最后
常量 EXTRA_FOO
(其中foo是您的密钥的名字)像<一个href="http://developer.android.com/reference/android/content/Intent.html#EXTRA_ALARM_COUNT">Intent.EXTRA_ALARM_COUNT
The convention used in the Android framework is to create public static final
constants named EXTRA_FOO
(where FOO is the name of your key) like Intent.EXTRA_ALARM_COUNT
常量的实际值是隔开的字符串,以避免冲突的名称:<一href="https://github.com/android/platform_frameworks_base/blob/59ed568fa5f723588de8ed0e2309b5d309931a2d/core/java/android/content/Intent.java#L3138/Intent.java"><$c$c>"android.intent.extra.ALARM_COUNT"$c$c>
The actual value of the constant is a name spaced string to avoid conflicts: "android.intent.extra.ALARM_COUNT"
如果您不希望创建活动之间的依赖与常量,那么你应该考虑把这些键为字符串值在您的strings.xml文件。我倾向于定义键XML时遵循相同的命名约定:
If you don't want to create dependencies between your Activities with constants, then you should consider putting these keys into string values within your strings.xml file. I tend to follow the same naming convention when defining the keys in xml:
<string name="EXTRA_MY_NAME">com.me.extra.MY_NAME</string>
它仍然读起来就像从Java端静态常量:
It still reads like a static constant from the Java side:
getString(R.string.EXTRA_MY_NAME);
这篇关于命名约定通过Android的额外传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!