我在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>
DrawingView
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);
}
}
}
答案 0 :(得分:2)
尝试getLayoutParams().height
,getLayoutParams().width
。 MATCH_PARENT
和WRAP_CONTENT
答案 1 :(得分:0)
您可以通过对onMeasure中的数据进行逆向工程来实现此目的。但是View并没有直接传递这些信息。相反,他们通过了一个MeasureSpec,它将给出EXACT,AT_MOST或者不确定的大小和常量,并让视图设置自己的大小。看看你们每个人得到的价值。