![](/img/trans.png)
[英]how to make button color variable in xml/java (android studio)
[英]How to use a variable in java within xml in Android Studio?
我正在尝试使用 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 方法中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.