在Android中将自定义布局视图扩展为布局扩展类
我在XML文件中定义了一个自定义布局,它有一个RelativeLayout根目录和一堆子视图 现在,我定义了以下类:在Android中将自定义布局视图扩展为布局扩展类,android,android-custom-view,layout-inflater,Android,Android Custom View,Layout Inflater,我在XML文件中定义了一个自定义布局,它有一个RelativeLayout根目录和一堆子视图 现在,我定义了以下类: public class MyCustomView extends RelativeLayout { public MyCustomView(Context context) { super(context); init(); } public MyCustomView(Context context, Attribut
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;
}
}
如您所见,我正在将root设置为MyCustomView
实例,并将attach标志设置为true
我想要实现的是,当我将这个自定义视图添加到另一个布局的xml中时,它将实例化MyCustomView
类,该类将在xml中定义布局
我已经尝试使用
标记,但这样我就失去了在XML中按自己的意愿排列子视图的能力
我还尝试膨胀XML并将其作为视图添加到MyCustomView
,但这样我就得到了冗余的RelativeLayout
最后,我添加了onMeasure()
只是为了完整性
发生膨胀,但未显示子视图
RelativeLayout
比您在onMeasure
布局中所做的要多一些(很多)(基本上,孩子们根本不用您的代码来衡量,所以他们没有什么东西可以展示)。如果扩展视图组
如RelativeLayout
,则需要让该类执行其回调(onMeasure
,onLayout
),或者至少要非常小心地复制方法,并根据需要对其进行修改(如果您想查看某些内容)
因此,删除
onMeasure
方法以查看孩子们,或者更好地解释为什么要覆盖它。您的问题是R.layout.widget\u view
中的视图不会出现在widget
组件中,对吗?没错。膨胀发生,但子视图未显示。@Daniel请确保已将其完全删除,如果发布my_custom_视图
layout文件,则不会有任何影响。谢谢,你说得对!顺便说一句,我添加了onMeasure()以强制使我的视图宽度和高度相等。你知道我怎样才能用不同的方式做到吗?