我有一个LinearLayout
(支架),它的宽度和高度都有match_parent
。在这个支架中,我插入了一个View
(扩展View
的类)。我在活动的onCreate
方法中执行此操作。
我的问题是,如何使这个子View
水平和垂直方向上最大限度地拉伸,保持正方形,以填充父 LinearLayout 中尽可能多的区域?
以下是我现在用作起点的内容:
pieContainer = (LinearLayout) findViewById(R.id.pie_container_id);
pie = new PieView(this);
pieContainer.addView(pie);
我尝试过在两端(主活动和PieView
类)覆盖 onMeasure 方法,但无济于事。
试试这个自定义的SquareView
。public class SquareView extends View {
public SquareView(Context context) {
super(context);
}
public SquareView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int size = Math.min(getMeasuredWidth(), getMeasuredHeight());
setMeasuredDimension(size, size);
}
}
我想你可以得到整个屏幕的宽度
DisplayMetrics display = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics( display );
int screenW = display.widthPixels;
并将View
的宽度设置为fill_parent
,将View
的高度设置为screenW
也许像这样:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, screenW); // (width, height)
yourView.setLayoutParams(params);
或者我可能完全误解了你的问题。这里很晚了,我累了:)如果是这样的话,对不起。
让我知道它是否有效:)