我想展示一个MyCustomLinearLayout
这延伸了LinearLayout
。我正在充气MyCustomLinearLayout
与android:layout_height="match_parent"
属性。
我想要的是展示一个ImageView
在这个MyCustomLinearLayout
。这个的高度ImageView
应该match_parent
,并且宽度应等于高度。我试图通过覆盖来实现这一点onMeasure()
方法。发生了什么,是这样的MyCustomLinearLayout
确实像它应该的那样变成了正方形,但是ImageView
没有显示。
下面是我使用的代码。请注意,这是我的问题的极其简化的版本。这ImageView
将被更复杂的组件所取代。
public MyCustomLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.view_myimageview, this);
setBackgroundColor(getResources().getColor(R.color.blue));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(height, height);
}
The view_myimageview.xml
file:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<ImageView
android:id="@+id/view_myimageview_imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/ic_launcher" />
</merge>
所以当我覆盖onMeasure()
方法,将ImageView
当我不覆盖时没有显示onMeasure()
方法,将ImageView
显示,但太小了,因为MyCustomLinearLayout
的宽度太小。