Android 以编程方式在LinearLayout中插入自定义视图,拉伸视图并使其呈方形
我有一个Android 以编程方式在LinearLayout中插入自定义视图,拉伸视图并使其呈方形,android,android-view,pie-chart,Android,Android View,Pie Chart,我有一个LinearLayout(支架),它的宽度和高度都有match\u parent。在这个支架中,我插入了一个视图(一个扩展视图的类)。我在活动的onCreate方法中执行此操作 我的问题是,如何使该子视图在水平和垂直方向上最大限度地拉伸,保持方形,以尽可能多地填充父线性布局的区域 以下是我现在使用的起点: pieContainer = (LinearLayout) findViewById(R.id.pie_container_id); pie = new PieView
LinearLayout
(支架),它的宽度和高度都有match\u parent
。在这个支架中,我插入了一个视图
(一个扩展视图的类
)。我在活动的onCreate
方法中执行此操作
我的问题是,如何使该子视图在水平和垂直方向上最大限度地拉伸,保持方形,以尽可能多地填充父线性布局的区域
以下是我现在使用的起点:
pieContainer = (LinearLayout) findViewById(R.id.pie_container_id);
pie = new PieView(this);
pieContainer.addView(pie);
我尝试过在两侧覆盖onMeasure方法(主要活动和
PieView
类),但没有效果。我想你可以得到整个屏幕的宽度
DisplayMetrics display = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics( display );
int screenW = display.widthPixels;
并将视图的宽度设置为填充父视图
,将视图的高度设置为屏幕W
可能是这样的:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, screenW); // (width, height)
yourView.setLayoutParams(params);
或者我可能完全误解了你的问题。现在很晚了,我很累:)如果是这样的话,我很抱歉
让我知道它是否有效:)试试这个自定义的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);
}
}
不幸的是,这不可用,因为我没有扩展活动
,而是扩展视图
。因此,getWindowManager()
不可用。