【发布时间】:2016-03-14 19:05:10
【问题描述】:
我正在开发一个 Android 应用程序,我在屏幕上画了一个红色圆圈。现在我想捕获布局参数“wrap_content”和“fill_parent”,因为我想通过onMeasureCallback() 函数更改每个参数布局类型的圆的大小。
如果我现在尝试,通过使用“wrap_content”和“fill_parent”,高度和宽度总是相同的。
activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#FFFFFF">
<com.example.myapplication.DrawingView
android:id="@+id/drawing_circle_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
<!--android:layout_width="wrap_content" // this must be a different width than by using fill_parent-->
<!--android:layout_height="wrap_content" // this must be a different height than by using fill_parent-->
/>
</LinearLayout>
绘图视图
public class DrawingView extends View {
// setup initial color
private final int paintColor = Color.RED;
// defines paint and canvas
private Paint drawPaint;
private float size;
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
// set standards
setFocusable(true);
setFocusableInTouchMode(true);
// setting up paint
setupPaint();
// set on measure call back
setOnMeasureCallback();
}
// Setup paint with color and stroke styles
private void setupPaint() {
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(size, size, size, drawPaint);
}
private void setOnMeasureCallback() {
ViewTreeObserver viewTreeObserver = getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
removeOnGlobalLayoutListener(this);
// how can I detect here which layout parameter I've used in the main_activity view?
}
});
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void removeOnGlobalLayoutListener(ViewTreeObserver.OnGlobalLayoutListener listener) {
if (Build.VERSION.SDK_INT < 16) {
getViewTreeObserver().removeGlobalOnLayoutListener(listener);
} else {
getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
}
}
【问题讨论】:
-
覆盖
onMeasure,不需要ViewTreeObserver
标签: android