我是 Android(Java) 新手,我的类(class)之一就是创建这个场景。
他们教导每个按钮使用不同的方法,但这增加了两种几乎相同的方法,我的干头脑说这不是最好的解决方案。
我写了一个BasketTeam
类:
package com.example.android.courtcounter;
import android.view.View;
import android.widget.TextView;
public class BasketTeam {
private TextView team;
public BasketTeam(View v) {
team = (TextView) v;
}
public void threePointsThrow(View v) {
this.addPoints(3);
}
public void twoPointsThrow(View v) {
addPoints(2);
}
public void freeThrow(View v) {
addPoints(1);
}
private void addPoints(Integer addedScore) {
Integer teamScore = Integer.parseInt((String) team.getText());
team.setText("" + (teamScore + addedScore));
}
public void resetScore() {
team.setText("" + 0);
}
}
在我的 MainActivity 中,我创建了 2 个实例作为公共(public) BasketTeam1
和 BasketTeam2
。
它们都很好,并且实例化得很好,因为在我的 MainActivity 中,我有一个名为 resetScore
的方法,使用它们并且它有效:
public void resetScore(View v) {
BasketTeam1.resetScore();
BasketTeam2.resetScore();
}
但是当我尝试使用我认为的这些类方法之一时,它找不到。 为什么?
这是我的尝试示例:
<Button
android:layout_height="wrap_content"
android:layout_width="120dp"
android:text="+3 points"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:id="@+id/team_1_3_points"
android:background="@color/colorAccent"
android:textColor="@android:color/white"
android:onClick="BasketTeam1.threePointsThrow"/>
更新
这是错误消息:
05-25 13:30:19.880 2345-2345/com.example.android.courtcounter E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.android.courtcounter, PID: 2345 java.lang.IllegalStateException: Could not find method BasketTeam1.threePointsThrow(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'team_1_3_points'
最佳答案
按钮的 onClick
属性必须对应于按钮上下文中的方法,通常是您的 MainActivity
。请参阅onClick .
解决方案可能是:
public class MainActivity extends Activity {
...
public void threePointsThrow(View v) {
switch (v.getId()) {
case R.id.team_1_3_points:
basketTeam1.threePointsThrow();
break;
case R.id.team_2_3_points:
basketTeam2.threePointsThrow();
break;
default:
break;
}
}
}
在布局中:
<Button
android:layout_height="wrap_content"
android:layout_width="120dp"
android:text="+3 points"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:id="@+id/team_1_3_points"
android:background="@color/colorAccent"
android:textColor="@android:color/white"
android:onClick="threePointsThrow"/>
关于java - 我可以在 Android View 中使用类方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37438491/