-
慕容3067478
我不知道是否有人还在读这个线程,但是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
-
守候你守候我
您可以通过创建自定义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>
-
隔江千里
我发现最好不要自己设置测量尺寸。父视图和子视图之间实际上需要进行一些协商,并且您不想重写所有这些代码。但是,您可以做的是修改measureSpecs,然后使用它们调用super。您的视图将永远不会知道它正在从其父级收到经过修改的消息,并将为您处理所有事情:@Overrideprotected 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);}