Fer*_*gre 5 android android-custom-view android-layout android-layout-weight
所以..我正在定义一个自定义视图/布局,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="3">
<Button
android:id="@+id/option_a"
style="?android:selectableItemBackground"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="One"
android:background="?android:selectableItemBackground"
android:textAppearance="?android:attr/textAppearanceButton"
android:textColor="@android:color/secondary_text_dark" />
<Button
android:id="@+id/option_b"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Two"
android:background="?android:selectableItemBackground"
android:textColor="@android:color/holo_red_dark"
android:textAppearance="?android:attr/textAppearanceButton" />
<Button
android:id="@+id/option_c"
style="?android:selectableItemBackground"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Three"
android:background="?android:selectableItemBackground"
android:textAppearance="?android:attr/textAppearanceButton"
android:textColor="@android:color/secondary_text_dark" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
结果:

但随后我在另一个布局中添加自定义视图,如下所示:
<com.xxx.xxx.xxx.ThreeStatePreference
android:id="@+id/mode"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Run Code Online (Sandbox Code Playgroud)
结果:

看起来这完全忽略了“重量”属性。我究竟做错了什么?
PD:我找到了一个代码解决方案:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int wspec = MeasureSpec.makeMeasureSpec(getMeasuredWidth()/getChildCount(), MeasureSpec.EXACTLY);
int hspec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY);
for(int i=0; i<getChildCount(); i++){
View v = getChildAt(i);
v.measure(wspec, hspec);
}
}
Run Code Online (Sandbox Code Playgroud)
但我想知道是否可以使用 XML 来完成此操作。
| 归档时间: |
|
| 查看次数: |
617 次 |
| 最近记录: |