My activity has a LinearLayout
with a single child view. I want both to fill the screen, minus a 12 dp margin.
Unfortunately, the child view is drawn 12 dp too big and gets cut off. Apparently match_parent
ignores the layout_margin
attribute when calculating the size of the child view. What is the simplest way to fix this?
myActivity.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>
myActivity.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);
}
}
myView.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!
}
}