3 回答
![?](http://img1.sycdn.imooc.com/533e564d0001308602000200-100-100.jpg)
TA贡献1773条经验 获得超3个赞
我不知道是否有人还在读这个线程,但是Jeff的解决方案只会使您半途而废(按字面意思)。他的onMeasure所要做的就是在一半的父对象中显示一半的图像。问题在于,在之前调用super.onMeasure setMeasuredDimension会根据原始大小测量视图中的所有子项,然后在setMeasuredDimension调整视图大小时将其切成两半。
相反,您需要调用setMeasuredDimension(根据onMeasure覆盖要求)并为LayoutParams视图提供一个新值,然后调用super.onMeasure。请记住,您LayoutParams是从视图的父类型派生的,而不是视图的类型。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth/2, parentHeight);
this.setLayoutParams(new *ParentLayoutType*.LayoutParams(parentWidth/2,parentHeight));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
我相信您唯一一次与父母有麻烦的地方就是父母LayoutParam
![?](http://img1.sycdn.imooc.com/54584d560001571a02200220-100-100.jpg)
TA贡献1802条经验 获得超10个赞
您可以通过创建自定义View并覆盖onMeasure()方法来解决此问题。如果您始终在xml中的layout_width中使用“ fill_parent”,则传递给onMeasusre()方法的widthMeasureSpec参数应包含父级的宽度。
public class MyCustomView extends TextView {
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth / 2, parentHeight);
}
}
您的XML看起来像这样:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
class="com.company.MyCustomView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
![?](http://img1.sycdn.imooc.com/54584ee0000179f302200220-100-100.jpg)
TA贡献1906条经验 获得超10个赞
我发现最好不要自己设置测量尺寸。父视图和子视图之间实际上需要进行一些协商,并且您不想重写所有这些代码。
但是,您可以做的是修改measureSpecs,然后使用它们调用super。您的视图将永远不会知道它正在从其父级收到经过修改的消息,并将为您处理所有事情:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int myWidth = (int) (parentHeight * 0.5);
super.onMeasure(MeasureSpec.makeMeasureSpec(myWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
}
- 3 回答
- 0 关注
- 786 浏览
添加回答
举报