2012-11-11 3 views
0

내 사용자 정의보기, ColorStrip을 내 응용 프로그램의 두 곳에서 사용합니다 : ListView 항목과 별도 FragmentActivity입니다. ListView 항목은 내보기를 올바르게 표시하지만 ColorStrip이 내 FragmentActivity에 대해 만들어진 이상한 이유로 hPxwPx 변수는 모든 숫자 중 102와 8에 각각 설정됩니다. ListView 항목에 대해이 변수의 값을 확인하면 (실행시 onCreate()) 모두 0으로 표시됩니다. 그러나 FragmentActivity에 대한 ColorStrip을 만들 때 이상한 값이 할당됩니다.전역 정수가 잘못된 값으로 할당 됨

나는 그것이 FragmentActivity을 위해 그것을 만들 때 변수가 0 이외의 값을 할당지고 이유를 이해하지 않습니다

다음

View의 내 서브 클래스에 대한 모든 코드입니다.

public class ColorStrip extends View { 

public ShapeDrawable mDrawable; 
private static int hPx = 0; 
private static int wPx = 0; 

public ColorStrip(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    mDrawable = new ShapeDrawable(new RectShape()); 

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, 
      R.styleable.ColorStrip, 0, 0); 
    try { 
     int color = a.getInt(R.styleable.ColorStrip_color, 0); 
     if (color != 0) 
      setColor(color); 
    } finally { 
     a.recycle(); 
    } 

} 

protected void onDraw(Canvas canvas) { 
    if (wPx == 0) 
     wPx = getWidth(); 
    if (hPx == 0) 
     hPx = getHeight(); 
    mDrawable.setBounds(0, 0, wPx, hPx); 
    mDrawable.draw(canvas); 
} 

public void setColor(int color) { 
    mDrawable.getPaint().setColor(color); 
} 
} 

여기 ListView의 XML :

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="horizontal"> 
<com.acedit.assignamo.ui.ColorStrip 
    android:id="@+id/assignment_list_color_strip" 
    android:layout_width="@dimen/color_strip_width" 
    android:layout_height="match_parent" /> 

과 FragmentActivity에 대한 XML :

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:ColorStrip="http://schemas.android.com/apk/res/com.acedit.assignamo" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <LinearLayout android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical"> 

    <com.acedit.assignamo.ui.ColorStrip 
     android:id="@+id/assignment_view_color_strip" 
     android:layout_width="match_parent" 
     android:layout_height="@dimen/assignment_view_color_strip_height" /> 

왜 변수가 이상한 값이 할당되고있다?

+1

정적으로 선언하지 마십시오. – auselen

+0

@auselen Aha! 이봐. 답으로 써 주시면 받아 드리겠습니다. – mightimaus

+0

나는 왜 내가 처음에 그것들을 정적이라고 선언했는지 의아해하고있다 ... 효율성상의 이유로 ... – mightimaus

답변

1

정적으로 hPx 및 wPx를 선언하지 마십시오. 또한 캐시하는 것이 아니라 onDraw에 대한 첫 번째 호출을 설정하는 것이 좋습니다. 더 좋은 장소는 Custom Drawing에 따른 View.onSizeChanged() 문서이며 http://android.developer.com에 있습니다.

+0

너비와 높이를 어떻게 설정 하겠는가? – mightimaus

+1

View.onSizeChanged http://developer.android.com/training/custom-views/custom-drawing.html#layouteevent – auselen

+0

고마워! 이제 내보기는 완전히 재사용 할 수 있습니다. – mightimaus

관련 문제