我在XML文件中定义了一个自定义布局,它有一个RelativeLayout根,带有一堆子视图。
现在,我定义了以下类:
public class MyCustomView extends RelativeLayout {
public MyCustomView(Context context) {
super(context);
init();
}
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.my_custom_view, this, true);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.d("Widget", "Width spec: " + MeasureSpec.toString(widthMeasureSpec));
Log.d("Widget", "Height spec: " + MeasureSpec.toString(heightMeasureSpec));
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int chosenWidth = chooseDimension(widthMode, widthSize);
int chosenHeight = chooseDimension(heightMode, heightSize);
int chosenDimension = Math.min(chosenWidth, chosenHeight);
setMeasuredDimension(chosenDimension, chosenDimension);
}
private int chooseDimension(int mode, int size) {
if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) {
return size;
} else {
return getPreferredSize();
}
}
private int getPreferredSize() {
return 400;
}
}
如您所见,我将根设置为MyCustomView
实例,将attach标志设置为true。
我想要实现的是,当我将这个自定义视图添加到另一个布局的xml中时,它将实例化将在XML中定义布局的MyCustomView
类。
我已经尝试使用<merge>
标记,但是这样我就无法根据需要在XML中安排我的子视图。
我还尝试对XML进行充气并将其作为MyCustomView
的视图添加,但这样我就变得多余RelativeLayout
。
最后,为了完整起见,我添加了onMeasure()
。
答案 0 :(得分:2)
通货膨胀发生但子视图未显示
RelativeLayout
比你在onMeasure
布局中所做的更多(很多)(基本上孩子们根本没有用你的代码测量,所以他们没有要展示的东西)。如果您扩展ViewGroup
RelativeLayout
,则需要让该类执行其回调(onMeasure
,onLayout
)或至少非常谨慎地复制方法并对其进行修改就像你想要的(如果你想看到的东西)。
因此,请移除onMeasure
方法以查看子项,或者更好地解释为什么要覆盖它们。