簡體   English   中英

Android-重新創建主動性-捆綁包

[英]Android - Recreating an acivity - Bundle

這是用於重新創建活動的代碼。

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

在這里,我對bundle的putInt()方法的定義有疑問。 當我尋找它的定義時,我得到了以下文檔-

public void putInt(字符串鍵,int值)
在API級別1中添加
將int值插入此Bundle的映射中,替換給定鍵的任何現有值。 參量
key:字符串,或者為null
值:一個int或null

我不明白String鍵在做什么? 我的意思是說,是那樣的。 每次將鍵用作將事物添加到捆綁軟件中的指針嗎? 此外,是否需要將STATE_SCORE定義為“ playerscore”?

您的字符串鍵不會做任何事情。 它就像一個哈希圖。 我不太明白您的最后一個問題,這是將鍵定義為常量的好方法。

Bundle就像字典一樣。 在字典中,您可以使用關鍵字來查找含義(或定義)。 這就是String的目的。 Bundle使用它來檢索鏈接到該鍵的值。

此外,是否需要將STATE_SCORE定義為“玩家得分”

嚴格來說,這不是必須的,但是如果您為密鑰聲明一個常量,並且始終使用代價高昂的方法從捆綁包中存儲/檢索值,則拼寫錯誤的可能性降低到接近零(由於調試時間過長,導致更多的頭緩存)

是否需要將STATE_SCORE定義為“ playerscore”。 Ans不可以直接給字符串

savedInstanceState.putInt("playerscore", mCurrentScore);

我不明白String鍵在做什么

它就像一個鍵值對。 當你這樣做

 savedInstanceState.putInt("playerscore", 1);

值1是存儲有鍵“ playerscore”的字符串,當您獲取時

savedInstanceState.getInt("playerscore");

這將返回1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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