我有一個包含多個活動和片段的專案。BuildConfig當除錯設定設定為true或取決于任何其他條件時,我正在嘗試在每個活動和片段的頂部添加一個橫幅以顯示“除錯模式” 。
我對如何實作這一點有一些想法,這些是:
- 有 2 個單獨的布局檔案,其中 1 個在除錯設定為真時加載。
- 創建一個加載到每個活動和片段上的片段。
我不確定實作這一目標的最佳方法是什么,甚至不知道從哪里開始
uj5u.com熱心網友回復:
我的第一反應是“為什么?”。但是您可以為此創建特定的布局。在 main/res/layout 你有 activity.xml 描述正常的布局。在 debug/res/layout 檔案夾中,只有在除錯版本中需要的額外內容,您才有相同的 activity.xml。請注意,您必須使這兩者保持同步。
沿著同一條線,您還可以為您想要的東西引入一種新的風格,但它有同樣的問題,即布局需要保持同步。
也許如果您解釋這樣做的原因,這將有助于提出更好的解決方案。
uj5u.com熱心網友回復:
我會在每個現有的 Activity 布局中添加一個水印 TextView。這樣您就不必管理同一布局的多個版本。您可以在布局膨脹后隱藏或顯示視圖。
如果你有多個活動,我會把它放在每個活動中。您至少不必對 Fragment 及其布局做任何事情。您可以將其放在一個單獨的布局檔案中,并將<include>其放在每個 Activity 布局中以減少代碼重復。
它應該有一個高海拔,所以它出現在所有東西的前面。并給它一個陰影,即使文本顏色與它后面的背景匹配,它也會可見。

<TextView
android:id="@ id/debugWatermark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:alpha=".5"
android:elevation="100dp"
android:shadowColor="#000000"
android:shadowRadius="5"
android:text="@string/debugBuild"
android:textColor="#FFFFFF"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="TextContrastCheck"
tools:visibility="visible" />
然后在您的活動(或活動)中,根據是否為除錯版本隱藏它:
//in onCreate:
binding.debugWatermark.visibility =
if (BuildConfig.DEBUG) View.VISIBLE else View.GONE
uj5u.com熱心網友回復:
我看到您的評論說您這樣做是為了讓測驗人員識別 APK 是除錯版還是發布版。
方法一
您可以使用此標志來顯示/隱藏僅需要為除錯構建顯示的特定視圖:
val isDebuggable = 0 != applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
if(isDebuggable)
thisisADebugApkTextView.visbility = View.VISIBILE
方法 2 (基于以下評論)
您可以創建一個 CustomTextView 來根據除錯狀態執行所有可見性邏輯
class CustomTextView(context: Context, attrs: AttributeSet? = null) : TextView(context, attrs) {
var isDebuggable = 0 != context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
init {
visibility = if(isDebuggable) View.VISIBLE else View.GONE
}
}
并在您的 XML 中使用它作為:
<com.path.to.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a debug build"/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/445652.html
