我想设计一个可以与任何屏幕分辨率的设备一起使用的应用程序。
我这样做的想法是为我使用的每种视图类型创建一个自定义视图,并使用 XML 中指定的layout_width和layout_height作为父大小的百分比(例如,layout_width="100dp"相当于fill_parent, 并且layout_width="50dp"意味着View的宽度将为父母的一半)。
这是TextView我制作的自定义类:
public class RSTextView extends TextView {
public RSTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int w, int h) {
int parentWidth = ((View)this.getParent()).getWidth();
int parentHeight = ((View)this.getParent()).getHeight();
Log.i(null, "Width: " + w + "; Height: " + parentHeight);
this.setMeasuredDimension(parentWidth * MeasureSpec.getSize(w) / 100,
parentHeight * MeasureSpec.getSize(h) / 100);
}
}
但是,它不起作用。和大小始终为 0 parentWidth。parentHeight
有没有更好的方法来创建具有相对大小的应用程序?
如果这是正确的方法,我怎样才能View从方法中检索“父母”的大小onMeasure?