2017-08-30 54 views
1

是否可以在EditText中僅爲某個buildtype設置文本? 我想在我開發的應用程序中運行調試構建類型時預填充EditText。 我現在看到的唯一方法是通過編程檢查當前的buildtype是否爲「debug」並調用setText()根據buildtype預填EditText

我希望能夠以更清潔的方式做到這一點。也許像XML佈局中的tools命名空間。 有什麼建議嗎?

回答

0

最後,我和我自己保持清潔的方式。 我已經看了Aspect Oriented Programming並且用AspectJ做了一個看點。

@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("[email protected]") 
      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

2

你可以把不同的環境有一定的文字在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" 
+0

謝謝,但我想避免在我的主要源代碼有這些字符串的文件。我最終使用了AOP解決方案,並在此發佈了自己的答案 – dumazy

0

另一種解決方案是創建調試和src目錄下釋放文件夾和有保留所有的公共資源與調試和釋放之間不同的值版。所以,你將有:

的\ src \發佈\水庫\值\ strings.xml中

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

的\ src \調試\ RES \ values \ strings.xml

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

,然後在XML

android:text="@string/your_string"

+0

謝謝,但我想避免在主源代碼中包含這些字符串文件。我最終選擇了AOP解決方案,並在此發佈了自己的答案 – dumazy