2017-02-18 125 views
0

我想建立一個自定義視圖,但似乎是我沒有得到的東西。Android的自定義視圖不正確的高度

我已經重寫了onSizeChanged和的onDraw方法,並增加在活動佈局我的自定義視圖並給它說100dp的高度,並將其按倒在底部,並開始與父母相對佈局的結束。 但是,視圖無法正確呈現,並且其下方有空白空白。下面

是我的onDraw和onSizedChanged方法

@Override 
    protected void onSizeChanged(int w, int h, int oldw, int oldh) { 
     viewHeight = h; 
     viewWidth = w; 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     // draw background 
     painter.setStrokeWidth(viewHeight); 
     painter.setColor(Color.BLUE); 
     canvas.drawLine(0, 0, viewWidth, 0, painter); 
    } 
下面

是怎麼了添加視圖佈局XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_registration" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:context="com.example.activities.RegistrationActivity"> 

     <com.example.custom.widgets.MyCustomView 
      android:id="@+id/holder" 
      android:layout_alignParentEnd="true" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentStart="true" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentBottom="true" 
      android:layout_width="match_parent" 
      android:layout_height="100dp"/> 

    <FrameLayout 
     android:layout_above="@+id/holder" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 
     <Button 
      android:text="kjdgfjkasdgfjkahsdgfjkhsa" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" /> 
    </FrameLayout> 
</RelativeLayout> 

這是它的外觀enter image description here

FWIW,我也嘗試將我的自定義視圖嵌入到FrameLayout中,並明確設置FrameLayout的高度並將我的自定義視圖的高度設置爲match_parent。仍然沒有成功。

+0

不過,你正在試圖解決的問題是神祕的對我。您是否希望自定義視圖僅爲100dp高度藍線? – azizbekian

+0

@azizbekian我想作爲layout_height屬性,在這種情況下,它100dp – Fouad

+0

'painter.setStrokeWidth(viewHeight)指定我的自定義視圖採取儘可能多的高度;'這行背後的邏輯是否正確?你是否試圖設置筆畫寬度100dp? – azizbekian

回答

0

在自定義視圖類重寫onMeasure()將設置你的視圖的依賴於由父提供的佈局約束的尺寸。

這應該給您的自定義查看100dp高度:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    int width = MeasureSpec.getSize(widthMeasureSpec); 
    int height = Math.min(100, MeasureSpec.getSize(heightMeasureSpec)); 
    setMeasuredDimension(width, height); 
} 

如果你改變了父母的約束,你將需要改變傳遞給方法的MeasureSpec值。看到這個問題:https://stackoverflow.com/a/12267248/7395923

更改的onDraw()方法是:

protected void onDraw(Canvas canvas) { 
    // draw background 
    painter.setStrokeWidth(getWidth()); 
    painter.setColor(Color.BLUE); 
    canvas.drawLine(0, 0, getWidth(), 0, painter); 
} 

,並清除onSizeChanged()方法。