2012-12-25 58 views
2

我的活動有一個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! 
    } 
} 
+1

嘗試在佈局中使用'android:padding =「12dp」'而不是'layout_margin'。 – fardjad

+0

查看我的評論Ridcully的回答。 –

回答

5

子視圖CA n在它們周圍有邊距,父視圖(或佈局等視圖組)可以在其邊界和子視圖之間填充。換句話說,保證金在視圖之外,填充在裏面。

而且,看到這樣出色的解釋:Difference between a View's Padding and Margin

例如使用標準視圖和填充,而不是保證金:

我創建了一個標準的觀點,而不是你自定義的一個小例子,用填充爲的LinearLayout作爲上述建議和它的作品完美(見截圖):

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:padding="12dp" 
    android:orientation="vertical" > 

    <View 
     android:layout_width="match_parent" 
     android:layout_height="100dp" 
     android:background="#ff0000"/> 
</LinearLayout> 

screenshot from layout editor

解決方案

事實證明,你在你的自定義視圖的onDraw方法使用canvas.getWidth()問題了。使用視圖的getWidth()來解決問題。最後:-)

+0

將layout_margin更改爲填充會使我面臨同樣的問題,除了外部佈局現在填充整個屏幕並且只有內部佈局具有12dp的邊距。我將繼續使用layout_margin。你知道是什麼導致我的問題? –

+0

也許這是你的自定義視圖的實現?你有沒有試過一個普通的'View'? – Ridcully

+0

我在子視圖的畫布上繪製線條。如果你願意,我可以發佈一個最小的測試用例。 –