我正在尝试使用TextView制作分数计数器。我已将文本设置为“0”,并希望每次按下按钮时它都会增加。我怎么能做到这一点?
到目前为止,我试图从活动的java中调用变量,但我不知道如何从xml中调用变量。或者从java更改xml的值。
任何帮助都非常感谢,并提前感谢。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="0"
android:id="@+id/score"
android:textSize="30sp"
android:textColor="@color/black_overlay"
android:layout_below="@+id/adView"
android:layout_centerHorizontal="true" />
这是我的xml,除了设置onclick方法之外,我目前在java部分中没有任何内容。
public void buttonOnClick (View view) {
Toast.makeText(getApplicationContext(), "Click", Toast.LENGTH_SHORT).show();
//String yourString = this.getResources().getString(R.string.scoreCount);
String mystring = getResources().getString(R.string.scoreCount);
}
试试这样吧
public void buttonOnClick (View view) {
Toast.makeText(getApplicationContext(), "Click", Toast.LENGTH_SHORT).show();
TextView score = (TextView) findViewById(R.id.score);
score.setText("your_score");
}
你可以尝试这样的事情:
int count = getResources().getInteger(R.integer.my_count);//why use string if you can use int
textView.setText(""+count++);//"" will cast count to string
严格来说,你无法在XML中真正存储变量。但是,您可以在字段中获取值,增加它并存储新值:
TextView view = (TextView) getViewById(R.id.score);
int score = Integer.parseInt(view.getText().toString());
view.setText(""+score++);
把它放在你的onClick方法中。