我的活动有一个LinearLayout
单子视图。我希望两者都填满屏幕,减去 12 dp 的边距。
不幸的是,子视图被绘制了 12 dp 太大并被切断。在计算子视图的大小时显然match_parent
忽略了该属性。layout_margin
解决此问题的最简单方法是什么?
我的活动.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.myapp.myView
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
我的活动.java
package com.myapp;
import android.app.Activity;
import android.os.Bundle;
public class myActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myActivity);
}
}
我的视图.java
package com.myapp;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class myView extends View {
private Paint paint = new Paint();
public myView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setColor(0xFFFF0000); //red
paint.setStyle(Paint.Style.STROKE); // for unfilled rectangles
paint.setStrokeWidth(4);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int size = canvas.getWidth(); // width = height (see onMeasure())
canvas.drawRect(0, 0, size, size, paint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
// This gives us a square canvas!
}
}