簡體   English   中英

如何在Android Studio的xml中使用java中的變量?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM