nha*_*man 1 android custom-controls
我试图展示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);
}
Run Code Online (Sandbox Code Playgroud)
该view_myimageview.xml文件中:
<?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>
Run Code Online (Sandbox Code Playgroud)
因此,当我覆盖onMeasure()方法时,ImageView没有显示,当我不覆盖onMeasure()方法时,ImageView显示,但方式太小,因为MyCustomLinearLayout宽度太小.
这不是您重写onMeasure方法,尤其是默认SDK布局的方法.现在使用您的代码,您只需将MyCustomLinearLayout方块分配给它一定的值.但是,你没有测量它的孩子,所以它们没有大小,也没有出现在屏幕上.
我不确定这会起作用,但试试这个:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int size = getMeasuredHeight();
super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY));
}
Run Code Online (Sandbox Code Playgroud)
当然这基本上会做onMeasure两次的工作,但ImageView现在应该可以填充它的父母.还有其他解决方案,但您的问题在细节上有点稀缺.