Noob Android开发者。
我正在为Android创建一个基本的美式足球计分应用程序。我正在尝试使用XML按钮的时钟递增变量值。
由于某种原因,单击增量按钮时,变量不会根据需要更新。我确定我错过了一些基本的东西,但似乎无法破解它。
<TextView
android:id="@+id/home_touchdowns_var"
android:layout_width="10dp"
android:layout_height="24dp"
android:layout_marginStart="80dp"
android:layout_marginTop="16dp"
android:text="0"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/home_touchdowns" />
<Button
android:id="@+id/home_touchdown_plus"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:onClick="homeTouchdownButtonPlus"
android:text="+"
app:layout_constraintStart_toEndOf="@+id/home_touchdowns_var"
app:layout_constraintTop_toBottomOf="@+id/home_touchdowns" />
package com.example.android.scorekeeper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int homeScore = 0;
int homeTouchdowns = 0;
int homeXtraPoints = 0;
int homeFieldGoals = 0;
int visitorScore = 0;
int visitorTouchdowns = 0;
int visitorXtraPoints = 0;
int visitorFieldGoals = 0;
public void homeTouchdownButtonPlus(View view) {
homeTouchdowns = homeTouchdowns + 1;
}
public void homeTouchdownsButtonMinus(View view) {
homeTouchdowns = homeTouchdowns - 1;
}
}
答案 0 :(得分:1)
[增订]
您的代码是正确的,但尚未完成,您必须调用TextView的方法setText
来更新视图数据,并且还必须在代码中映射TextView,因此您的代码将是:
private TextView textview_home_touchdowns; //TextView where you will see the data
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview_home_touchdowns = (TextView) //Mapping the TextView
findViewById(R.id.home_touchdowns_var);
}
public void homeTouchdownButtonPlus(View view) {
homeTouchdowns = homeTouchdowns + 1;
textview_home_touchdowns.setText(homeTouchdowns+""); //Updating the TextView as String
}
public void homeTouchdownsButtonMinus(View view) {
homeTouchdowns = homeTouchdowns - 1;
textview_home_touchdowns.setText(homeTouchdowns+"");
}
感谢@Martin De Simone进行更正
答案 1 :(得分:1)
@DigaoParceiro是对的,你忘了调用setText(),但如果按照他的方式执行它会抛出异常,因为setText方法需要String不是整数,使用它。
public void homeTouchdownButtonPlus(View view) {
homeTouchdowns = homeTouchdowns + 1;
textview_home_touchdowns.setText(String.valueOf(homeTouchdowns)); //Updating the View
}
public void homeTouchdownsButtonMinus(View view) {
homeTouchdowns = homeTouchdowns - 1;
textview_home_touchdowns.setText(String.valueOf(homeTouchdowns));
}