Android 全局整数被分配了错误的值
我在应用程序中的两个位置使用自定义视图,Android 全局整数被分配了错误的值,android,android-view,Android,Android View,我在应用程序中的两个位置使用自定义视图,ColorStrip:在ListView项中和在单独的片段活动中。ListView项正确显示我的视图,但由于某些奇怪的原因,当为我的碎片活动创建色带时,hPx和wPx变量分别设置为102和8。如果我在为ListView项创建这些变量时(在执行onCreate()期间)检查这些变量的值,它们都显示为零。但是在为我的FragmentActivity创建色带时,会为它们分配这些奇怪的值 我不明白为什么在为FragmentActivity创建变量时,变量会得到除0
ColorStrip
:在ListView
项中和在单独的片段活动中。ListView项正确显示我的视图,但由于某些奇怪的原因,当为我的碎片活动创建色带时,hPx
和wPx
变量分别设置为102和8。如果我在为ListView项创建这些变量时(在执行onCreate()
期间)检查这些变量的值,它们都显示为零。但是在为我的FragmentActivity创建色带时,会为它们分配这些奇怪的值
我不明白为什么在为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" />
以及碎片活动的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" />
为什么要给变量分配这些奇怪的值?不要将hPx和wPx声明为静态。另外,缓存它们并不是一个好主意,只需在第一次调用onDraw时进行设置。更好的位置是根据位于的文档。@auselen Aha!Duh.(facepalm)把它写下来作为答案,我会接受的。我想知道为什么我一开始就把它们声明为静态的…一定是出于效率的原因…你建议我如何设置我的宽度和高度?View.onSizeChanged谢谢!现在我的视图完全可以重复使用了。