2012-06-30 285 views
1

我正在嘗試使用寬度作爲高度來製作正方形的自定義視圖。我也在使用預先定義的佈局,因爲它是UI,所以我膨脹了。只要我覆蓋onMeasure,自定義視圖就不會再出現。這裏是我的代碼:Android:自定義視圖

public class MyView extends RelativeLayout{ 

    public MyView(Context context) { 
     super(context); 
     addView(setupLayout(context)); 
    } 

    public MyView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     addView(setupLayout(context)); 
    } 

    public MyView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     addView(setupLayout(context)); 
    } 

    private View setupLayout(Context context) { 
     LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View myView = inflater.inflate(R.layout.view_layout, null); 
     return myView; 
    } 

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(widthMeasureSpec)); 
    } 

} 

我有2個問題:

  1. 如何重寫onMeasure使得它吸引我的看法,我期待它的方式?
  2. 有沒有什麼辦法可以讓這個視圖層次結構方面更有效(即不能把一個RelativeLayout的內部的RelativeLayout)
+1

@trumpetlicks [RlativeLayout是View的後代](http://developer.android.com/reference/android/widget/RelativeLayout.html)。你的第二點是什麼? – Sam

+0

這是一個奇蹟,這個編譯。你有一個不同的類的構造函數(MenuButton)。 – tiguchi

+1

@NobuGames我很樂意猜測這是作者類的簡化版本。作者覺得有必要改變類名,他們只是忘了改變那個構造函數的名字。沒有必要諷刺,我願意猜測你也不完美。 – Sam

回答

1

您可以使用此代碼Jan Němec's answer to a similar question

import android.content.Context; 
import android.util.AttributeSet; 
import android.widget.LinearLayout; 

public class SquareLayout extends LinearLayout { 

public SquareLayout(Context context) { 
    super(context); 
} 

public SquareLayout(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 

     int width = MeasureSpec.getSize(widthMeasureSpec); 
     int height = MeasureSpec.getSize(heightMeasureSpec); 

     if (width > (int)(mScale * height + 0.5)) { 
      width = (int)(mScale * height + 0.5); 
     } else { 
      height = (int)(width/mScale + 0.5); 
     } 

     super.onMeasure(
       MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), 
       MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) 
     ); 
    } 
    } 

或嘗試使用this庫項目。

+0

不要複製其他用戶的答案! – Luksprog

+0

是被禁止的嗎?我們在這裏作爲社區互相幫助,主要目標是分享信息!無論如何,我編輯了我的答案與原來的鏈接。 –

+0

分享答案不是複製答案並將其作爲自己的傳遞,而沒有任何指向原始資源的鏈接。我沒有看到你的答案有任何修改。 – BoltClock