我的活動有一個LinearLayout
與單個子視圖。我希望既能填滿屏幕,又能減去12dp的餘量。Android - match_parent忽略layout_margin
不幸的是,孩子的觀點是繪製12DP太大,被切斷。當計算子視圖的大小時,顯然match_parent
忽略layout_margin
屬性。解決這個問題的最簡單方法是什麼?
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!
}
}
嘗試在佈局中使用'android:padding =「12dp」'而不是'layout_margin'。 – fardjad
查看我的評論Ridcully的回答。 –