2

是否可以EditText仅为特定构建类型设置文本?我希望EditText在运行调试构建类型时预填充我正在开发的应用程序。我现在看到这一点的唯一方法是通过编程检查当前当前构建类型是否为“调试”并调用setText().

我希望能够以更清洁的方式做到这一点。可能类似于toolsXML 布局中的命名空间。有什么建议么?

4

3 回答 3

3

您可以在build.gradel文件中为不同环境放置一些文本buildTypes

//For Development Environment
buildConfigField "String", "text", "\"DEVELOPMENT ENVIRONMENT TEXT\""

//For Live Environment leave it empty
buildConfigField "String", "text", "\"\""

然后在活动中直接将其设置为您的edittext,而无需手动检查任何内容。

etValue.setText(BuildConfig.text);

更优选的解决方案(对于直接 XML)

而不是buildConfigField使用resValue它将String Resource在项目重建时为不同的环境生成一个。

//For Live Environment leave it empty
resValue "string", "text", YOUR_STRING_LIVE

//For Development Environment
resValue "string", "text", YOUR_STRING_DEVELOPMENT

你可以直接在xml中使用它

android:text="@string/text"
于 2017-08-30T07:57:41.793 回答
0

另一种解决方案是在您的 src 文件夹下创建调试和发布文件夹,并在调试和发布版本之间保留所有具有不同值的公共资源。所以你将拥有:

\src\release\res\values\strings.xml

  <string name="your_string">release_value_here</string>

\src\debug\res\values\strings.xml

  <string name="your_string">debug_value_here</string>

然后在 XML

android:text="@string/your_string"

于 2017-08-30T08:22:36.667 回答
0

最终,我以自己的方式保持清洁。我看过 Aspect Oriented Programming 并用 AspectJ 做了一个 Aspect。

@Aspect
class PrefillAspect {

    @After("execution(* com.example.aspect.LoginActivity.onCreate(*))")
    fun prefillLoginForm(joinPoint: JoinPoint) {
        try {
            val activity = joinPoint.target as LoginActivity
            activity.findViewById<EditText>(R.id.editEmail).setText("test@example.com")
            activity.findViewById<EditText>(R.id.editPassword).setText("MySecretPassword")
        } catch (e: Throwable) {
            Log.e("PrefillAspect", "prefillLoginForm: failed")
        }
    }

}

我已将此方面添加到我的src/debug/java文件夹中,因此此方面仅在运行调试构建时应用。我的主要源代码中没有任何代码,因此永远不会发布,并且代码库保持干净。

我在这里写了一篇关于这个的文章:https ://medium.com/@dumazy/prefill-forms-on-android-with-aspectj-97fe9b3b48ab

于 2017-09-01T21:24:33.633 回答