相关疑难解决方法(0)

当覆盖onMeasure时,自定义LinearLayout的膨胀子项不会显示

我试图展示MyCustomLinearLayout哪个延伸LinearLayout.我正在MyCustomLinearLayoutandroid: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" …
Run Code Online (Sandbox Code Playgroud)

android custom-controls

1
推荐指数
1
解决办法
2580
查看次数

标签 统计

android ×1

custom-controls ×1