簡體   English   中英

如何在課程之間共享變量?

[英]How do I share variables between classes?

假設我正在做類似測驗的事情,並且我有一個計數器來顯示已正確回答的問題數量。 正確回答一個問題並顯示新的屏幕(活動)時,如何將數字轉入下一屏幕?

當您說屏幕時,您是指活動嗎? 然后,您可能希望通過意圖中的附加內容傳遞它們。

活動1:

    int score;

    ...
    Intent Intent = new Intent(...);
    intent.putExtra("score_key", score);
    startActivity(intent);

活動2的onCreate()

    int score;
    ...

    Bundle extras = getIntent().getExtras();

    // Read the extras data if it's available.
    if (extras != null)
    {
        score = extras.getInt("score_key");
    }

您可以隨心所欲地捆綁發送數字,字符串等。

Bundle b = new Bundle();
b.putInt("testScore", numCorrect);
Intent i = new Intent(this, MyClass.class);
i.putExtras(b);
startActivity(intent)

您還可以將StringArrays和其他一些簡單的變量

您可以通過這種方式之一在整個項目中共享數據,

public class mainClass 
{
    private static int sharedVariable = 0;


    public static int getSharedVariable()
    {
          return sharedVariable;
    }
}

在其他類/活動中,您可以直接使用classname和進行訪問。 (點)運算符。 例如mainClass.getSharedVariable();

在Activitiys中存儲變量的一個好習慣是使用Application類的自己的實現。

public class MyApp extends android.app.Application {

private String myVariable;

public String getMyVariable() {
    return myVariable;
}

public void setMyVariable(String var) {
    this.myVariable = var;
}

在應用程序標簽內的Manifest.xml中添加新的類:

<application android:name="MyApp" android:icon="@drawable/icon" android:label="@string/app_name">

現在,您可以按以下方式在每個Activity中操作變量:

MyApp ctx = (MyApp)getApplicationContext();
String var = ctx.getMyVariable();

暫無
暫無

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

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