我有一个button
扩展的习惯View
。在构造函数中,我设置了一个成员变量来保存 XML 定义中设置的自定义属性。目前在 XML 中定义了 5 个这样的按钮,每个按钮都附加了一个不同的 int 来表示一个阶段。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.mycompany.stagedApp"
android:layout_width="match_parent"
android:orientation="horizontal"
style="@style/stepFooter">
<com.mycompany.stagedApp.StepButtonView
android:text="@string/step_one_icon"
style="@style/numberedIcon"
android:id="@+id/step_one_button"
custom:stepNumber="1"
android:background="@drawable/circle" />
<com.mycompany.stagedApp.StepButtonView
android:text="@string/step_two_icon"
style="@style/numberedIcon"
android:id="@+id/step_two_button"
custom:stepNumber="2"
android:background="@drawable/circle" />
<com.mycompany.stagedApp.StepButtonView
android:text="@string/step_three_icon"
style="@style/numberedIcon"
android:id="@+id/step_three_button"
custom:stepNumber="3"
android:background="@drawable/circle" />
<com.mycompany.stagedApp.StepButtonView
android:text="@string/step_four_icon"
style="@style/numberedIcon"
android:id="@+id/step_four_button"
custom:stepNumber="4"
android:background="@drawable/circle" />
<com.mycompany.stagedApp.StepButtonView
android:text="@string/step_five_icon"
style="@style/numberedIcon"
android:id="@+id/step_five_button"
custom:stepNumber="5"
android:background="@drawable/circle" />
</LinearLayout>
在StepButtonView.java
我有:
class StepButtonView extends View {
private static int stepNumber;
public StepButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.custom_values);
stepNumber = ta.getInt(R.styleable.custom_values_stepNumber, 0);
// This log correctly displays the numbers 1 - 5
Log.d("StepFromCustom in constructor", String.format("%d",StepButtonView.stepNumber));
this.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
Log.d("Step", String.format("%d", view.getId()));
// This log only displays the last number 5
Log.d("StepFromCustom", String.format("%d",StepButtonView.stepNumber));
}
});
}
}
当activity
开始并构建每个按钮时,将记录数字 1 -5。但是,单击时记录的数字始终是 5,最后一个stepNumber
. 在onClick listener
它列出了一个不同的 ID 值但相同stepNumber
,所以我最初认为它指的是同一个对象一定是不正确的。
谁能解释发生了什么,以及为什么,因为我认为这是对我显然需要澄清的语言的误解。