一個簡單的 CustomViewGroup 是這樣的:
// kotlin
class MyLayout : ConstraintLayout {
init{
inflate(... R.layout.my_layout ...)
}
}
<!-- my_layout.xml -->
<ConstraintLayout ...>
<TextView .../>
<Button .../>
</ConstraintLayout>
但是,這是一個問題。布局級別是這樣的:
ConstraintLayout
ConstraintLayout
TextView
Button
有一個額外的嵌套ConstraintLayout
。
有沒有辦法洗掉嵌套布局?
有一些不好的解決方法:
(1) 使用 <merge/>
像這樣更改xml:
<!-- my_layout.xml -->
<merge ...>
<TextView .../>
<Button .../>
</merge>
但問題是對xml進行后續修改不方便。
(2) 將 xml 根目錄更改為 MyLayout。
<!-- my_layout.xml -->
<MyLayout ...>
<TextView .../>
<Button .../>
</MyLayout>
但問題是您只能從LayoutInflater.inflate(R.layout.my_layout)
.
您不能像new MyLayout(...)
(for java) 或<MyLayout .../>
(for xml) 那樣呼叫 MyLayout。
并且違反了脫鉤原則。
那么,洗掉額外嵌套 ViewGroup 的最佳解決方案是什么?
求助~~~~~ :)
參考
- Android 中自定義視圖的美妙之處以及操作方法!
更新
固定 - 就像這樣:
<merge
tools:parentTag="android.widget.RelativeLayout"
tools:layout_width="match_parent"
tools:layout_height="match_parent"
... />
看:
- <merge/> 在自定義 View xml 布局中
uj5u.com熱心網友回復:
固定 - 就像這樣:
<merge tools:parentTag="android.widget.RelativeLayout"
...>
<TextView .../>
<Button .../>
</merge>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/506983.html
上一篇:膨脹類com.paypal.checkout.paymentbutton.PaymentButtonContainer時出錯